天天看点

关于 Angular Component ngOnDestroy 钩子函数的调用时机

我开发了一个 Angular Component,实现了 ngOnDestroy 钩子方法之后,没有找到其被调用的方法。查看这个StackOverflow链接后,得知无论是我刷新浏览器,还是从当前页面路由到一个新的页面,都不会触发 ngOnDestroy.

On refresh or when you navigate away from the current page, then ngOnDestroy won’t be called. The application will just be destroyed by the browser.

Only when Angular2 removes the component from the DOM because you move away or you call destroy() on a dynamically created component, then ngOnDestroy() is called.

只有当 Component 从 DOM 中被移除,或者显式调用一个动态创建的 Component 实例的 destroy 方法,才能触发 ngOnDestroy.

关于 Angular Component ngOnDestroy 钩子函数的调用时机

我点击 navigate to 跳转之前,DOM 元素如下图所示:

关于 Angular Component ngOnDestroy 钩子函数的调用时机
关于 Angular Component ngOnDestroy 钩子函数的调用时机

点了跳转后,browser-test 元素确实从 DOM 中消失了:

关于 Angular Component ngOnDestroy 钩子函数的调用时机
关于 Angular Component ngOnDestroy 钩子函数的调用时机

然而我在该 DOM 节点上设置的 Break on node removal 并没有触发,感觉这个跳转像是一次页面刷新:

关于 Angular Component ngOnDestroy 钩子函数的调用时机
关于 Angular Component ngOnDestroy 钩子函数的调用时机

继续阅读