Angular2+ 编译后部署到服务器上页面刷新404问题

前端之家收集整理的这篇文章主要介绍了Angular2+ 编译后部署到服务器上页面刷新404问题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

原因:NG2+ 会默认不显示URL后面的文件

解决方案:使用LocationStrategy方式,然后把URL后的# 替换成index.html#

app.module.ts

 1 import {HashLocationStrategy,LocationStrategy} from ‘@angular/common‘;  2 
 3 @NgModule({
 4   imports: [  ], 5   declarations: [
 6     AppComponent, 7   ], 8   providers: [{provide: LocationStrategy,useClass: HashLocationStrategy}], 9   bootstrap: [AppComponent]
10 })
11 export class AppModule { }

app.component.ts

1   changeURL() {
2     var text = window.location.href;
3     text.toString();
4     var url = text.replace(/\/#/,"/index.html#");
5     window.history.pushState({},"0",url);
6   }
7   ngAfterContentChecked(){// 每次做完组件视图和子视图的变更检测之后调用,为了防止循环替换,replace使用全替换模式
8     this.changeURL();
9   }

猜你在找的Angularjs相关文章