假设一个组件有两个生命周期钩子:
{
ngAfterContentInit() {
this.subscription = rx.Observable
.interval()
.subscribe(value => this.value = value)
},
ngOnDestroy() {
this.subscription.unsubscribe()
}
}
是否可以在ngOnDestroy
之前调用ngAfterContentInit
,如果是,为什么要这么做?在我的应用程序中,在足够快的组件插入/删除过程中似乎就是这种情况。文档不清楚这个主题。
我问这个问题是否ngOnDestroy
不应该假设其他生命周期回调中的任何内容都已定义,而且防弹ngOnDestroy
应该执行状态检查,如下所示:
ngOnDestroy() {
this.subscription && this.subscription.unsubscribe()
}
答案 0 :(得分:2)
The documentation对生命周期钩子的顺序非常清楚,并没有考虑改变顺序的可能性。
此外,正如在this example中可以看到的,组件编译过程是同步的。如果要加载模板,则在编译之前请求它们。
初始化应该导致此日志:
bootstrap
bootstrap tick
constructor
ngOnInit
ngAfterContentInit
ngAfterViewInit
constructor tick
对于同步操作,某些代码没有机会“更快”。并且无序。
this.subscription && ...
不需要检查。