【发布时间】:2020-12-23 11:37:24
【问题描述】:
我在 Angular (v.10) 中遇到了一个奇怪的问题。场景如下。
当我通过 js 或 routeLink 加载 URL 例如:'this.router.navigate(['/test']);测试组件只调用一次构造函数或ngOnInit。这种行为是正常的,没有问题。(这个我已经通过console.log验证了)。
但问题是,当我重新加载/刷新 URL 时,例如:'http://localhost:4200/#/test',测试组件类将调用 constructor/ngOnInit 两次。 (console.log 打印两次内容)。
所有路由都存在此问题,并且仅在重新加载页面时才会发生。
这是我的代码详细信息。
app.component.html
<router-outlet></router-outlet>
app-routing.module.ts
{
path: 'test',
component: TestComponent
},
测试组件.ts
export class TestComponent {
constructor(){
//this will print two times only when page reload/refresh
console.log("test");
}
}
我找不到问题的根本原因。如果需要,我会提供更多详细信息。
【问题讨论】:
-
如果我们有你的路由模块的全貌会更好,或者更好地分享一个stackblitz.com
-
一些提示:1) 检查浏览器/提琴手的网络选项卡中发生的情况 2) 您使用的是 {provide: LocationStrategy, useClass: HashLocationStrategy} 还是 RouterModule.forRoot(routes, { useHash: true }) ? 3)尝试使用另一个本地服务器(例如:http-server)
标签: angular typescript