在ngAfterViewInit中使用destroyDetection的销毁视图

时间:2018-01-24 12:14:45

标签: javascript angular

我工作的组织中的私有(但开源)Angular包有一些代码如下:

ngAfterViewInit(): void {
  setTimeout(() => {
    this.changeDetector.detectChanges();
    // do more things
  });
}

我们在我们的应用程序中实现了这个包(该包用于引入通用组件,以便组织的前端开发人员不会多次实现,并强制执行通用设计语言以保持一致性)。但是,当使用组件时,会调用它,并显示然后重复销毁组件,最终它将停止工作,在控制台中出现此错误:

Error: ViewDestroyedError: Attempt to use a destroyed view: detectChanges

我试图找到一种方法来确保如果组件已经被销毁,则上面的代码没有被运行。我考虑过使用ngOnDestroy生命周期方法:

ngOnDestroy(): void {
  this.changeDetector.detach();
}

但是我不知道还有什么我会在那里检查视图是否正常。我也考虑过这样的事情:

if (!this.changeDetector.destroyed) {
  this.changeDetector.detectChanges();
}

destroyed上没有ChangeDetectorRef之类的内容。

确保此错误未显示且组件正常工作的正确方法是什么,即使重复显示和销毁它也是如此?

2 个答案:

答案 0 :(得分:6)

我认为我找到的最佳解决方案是使用!ViewRef.destroyed,如果返回truthy然后继续,否则不要。

if (!(this.changeDetector as ViewRef).destroyed) {
  this.changeDetector.detectChanges()
  // do other tasks
}

答案 1 :(得分:1)

我认为毁坏确实有效,但语法是这样的:

if (!this.changeDetector['destroyed']) {
    this.changeDetector.detectChanges();
}

然后很明显,只需将您的代码保存在ngOnDestroy挂钩上。