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(这一步是后端Tomact不设置默认index.html的情况下才需要的)

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   }

 详细内容可浏览下一遍文章《Angular2+URL中的 # 引发的思考》

原文地址:https://www.cnblogs.com/Failbs/p/9645860.html