首页 文章

为什么每次重复调用ngOnInit

提问于
浏览
1

Per Angular(https://angular.io/api/core/OnInit表示ngOnInit在第一次检查指令的数据绑定属性之后以及在检查其任何子项之前调用 . 在实例化指令时仅调用一次 . ),

所以ngOnInit应该被调用一次,但是如plunker(即https://angular.io/tutorial/toh-pt5的副本)所示,我只修改了app / heroes / heroes.component.ts和app / dashboard / dashboard.component.ts来安装console.log

当打开F12(开发人员工具)时,控制台会在路径更改时重复显示日志 .

我看了why ngOnInit called twice?Difference between Constructor and ngOnInitAngular 2 App Component ngOnInit called twice when using iframengOnInit called everytime i change route

但无法理解为什么每次都会调用ngOnInit .

console.log("ngOnInit in All Heroes");
console.log("ngOnInit InDashBoard");

2 回答

  • 0

    当路由更改时,组件被销毁,然后当路由更改时,组件将再次初始化 .

    将其添加到 DashboardComponent 以便自己查看:

    ngOnDestroy() {
      console.log("ngOnDestroy InDashBoard");
    }
    
  • 3

    在我的案例中,问题是我引导子组件的方式 . 在我的 @NgModule 装饰器的元数据对象中,我在bootstrap属性中传递 child component 以及 parent component . 在bootstrap属性中传递子组件是重置我的子组件属性并使 OnInit() 被触发两次 .

    @NgModule({
     imports: [ BrowserModule,FormsModule ], // to use two-way data binding ‘FormsModule’
    declarations: [ parentComponent,Child1,Child2], //all components
     //bootstrap: [parentComponent,Child1,Child2] // will lead to errors in binding Inputs in Child components
     bootstrap: [parentComponent] //use parent components only
     })
    

相关问题