【问题标题】:Component instance creating twice in angular only when page reloading组件实例仅在页面重新加载时以角度创建两次
【发布时间】: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


【解决方案1】:

经过多次尝试,我找到了问题所在。 我在我的 Angular 项目中使用 HMR(热模块替换),这会导致组件在页面重新加载时初始化两次。我已禁用 HMR,现在工作正常。

【讨论】:

    猜你喜欢
    • 2022-01-12
    • 1970-01-01
    • 2017-10-22
    • 2017-11-22
    • 1970-01-01
    • 2020-09-13
    • 2012-06-15
    • 2013-06-25
    • 1970-01-01
    相关资源
    最近更新 更多