假设一个组件有两个生命周期钩子(Hook):
{
ngAfterContentInit() {
this.subscription = rx.Observable
.interval()
.subscribe(value => this.value = value)
},
ngOnDestroy() {
this.subscription.unsubscribe()
}
}
是否有可能在 ngAfterContentInit
之前调用 ngOnDestroy
,如果可以,为什么?在我的应用程序中足够快的组件插入/移除期间似乎就是这种情况。文档不清楚这个主题。
我问这个问题是想知道 ngOnDestroy
是否不应该假设来自其他生命周期回调的任何东西都已定义,并且防弹 ngOnDestroy
应该执行存在性检查,如下所示:
ngOnDestroy() {
this.subscription && this.subscription.unsubscribe()
}
最佳答案
The documentation生命周期钩子(Hook)的顺序非常清楚,没有考虑改变顺序的可能性。
此外,在this example中可以看出,组件编译过程是同步的。如果有模板要加载,则在编译之前请求它们。
初始化应该产生这个日志:
bootstrap
bootstrap tick
constructor
ngOnInit
ngAfterContentInit
ngAfterViewInit
constructor tick
对于同步操作,一些代码没有机会变得“更快”并乱序运行。
this.subscription && ...
不需要检查。
关于angular - ngOnDestroy 可以在 ngAfterContentInit 之前发生吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41207317/