为什么ngOnInit每次都会被反复调用 [英] Why ngOnInit is getting called every time repeatedly

查看:474
本文介绍了为什么ngOnInit每次都会被反复调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每个Angular( https://angular.io/api/core/OnInit 表示 ngOnInit是在首次检查指令的数据绑定属性之后,在检查其任何子级之前调用的.在实例化指令后仅调用一次.),

Per Angular ( https://angular.io/api/core/OnInit that says ngOnInit is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated. ),

因此应该调用一次ngOnInit,但是如 plunker 中所示是 https://angular.io/tutorial/toh-pt5 )的副本,仅修改 app/heroes/heroes.component.ts app/dashboard/dashboard.component.ts 具有console.log

So ngOnInit should be called once, but as shown in the plunker ( that is a copy from https://angular.io/tutorial/toh-pt5 ) , I only modified app/heroes/heroes.component.ts and app/dashboard/dashboard.component.ts to have console.log

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

and when F12 (Developer Tools) is opened, the console shows the log repeatedly when route is changed.

我看了看 为什么ngOnInit被调用两次?构造函数与ngOnInit之间的区别使用iframe时,Angular 2 App组件ngOnInit调用了两次每次更改路线时都会调用的ngOnInit

I looked why ngOnInit called twice? , Difference between Constructor and ngOnInit , Angular 2 App Component ngOnInit called twice when using iframe , ngOnInit called everytime i change route

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

but could not understand why ngOnInit is being called everytime.

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

推荐答案

当路线更改时,组件被销毁 ,然后,当路线更改返回时,组件被初始化.再次.

When the route changes the component is destroyed, then when the route changes back the component is initialised again.

将此添加到DashboardComponent中以自己查看:

Add this to DashboardComponent to see for yourself:

typescript
    ngOnDestroy() {
      console.log("ngOnDestroy InDashBoard");
    }

这篇关于为什么ngOnInit每次都会被反复调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆