angular - ngOnDestroy 可以在 ngAfterContentInit 之前发生吗?

标签 angular angular2-directives

假设一个组件有两个生命周期钩子(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/

相关文章:

angular - 为什么 Angular 2 有模板的 JiT 编译?

Angular 2动态标签加载器

angular - 基于条件的一个组件多个模板

javascript - Angular - 指令的输入在按下按钮时不更新

angular - 实现操作 Dom 的第 3 方库的正确方法是什么?

Typescript 装饰器 vs 类继承

angular 2 ngModel 使用 Elvis 运算符解析错误

javascript - D3 V4 与 Angular-cli

javascript - 从 Angular 6 中的重复控制中获取值

Angular 2/4 : How to check length of input's value using directive?