【发布时间】:2017-12-13 07:23:02
【问题描述】:
Error: ViewDestroyedError: Attempt to use a destroyed view: detectChanges at viewDestroyedError
我在尝试通过在组件中使用detectChanges 方法触发更改检测时转到另一个页面时收到此错误。我发现如果我使用 markForCheck 方法,我不会收到错误消息。我知道这两种方法的区别,但我只是不明白为什么detectChanges 会在销毁过程中导致此错误。有什么想法吗?
import { Component, ChangeDetectorRef, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class ChildComponent implements OnInit {
data: any;
constructor(
private changeDetector: ChangeDetectorRef,
private somethingService: SomethingService
) {
}
ngOnInit() {
this.somethingService.getData().subscribe(data => {
this.data = data;
this.changeDetector.detectChanges();
});
}
}
【问题讨论】:
-
请在stackblitz.com上发布允许复制的代码——理想情况下是最小的工作复制
-
@GünterZöchbauer 添加了一些代码
-
你在组件被销毁后触发
detectChanges。添加ngOnDestroy你会看到它被触发了 -
@AngularInDepth.com 我想通了,但是为什么在组件被销毁后会触发更改检测器?
-
@DongBinKim,因为你用
detectChanges触发它
标签: angular