为什么detectChanges方法会导致“尝试使用损坏的视图”错误?

Don*_*Kim 2 angular

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();
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 5

无需致电 detectChanges

如果仍要使用它,则还可以确保销毁该可观察对象。

serviceSubscription:any
ngOnInit() {
    this.serviceSubscription = this.somethingService.getData().subscribe(data => {
        this.data = data;
        this.changeDetector.detectChanges();
    });
}

ngOnDestroy() {
  this.serviceSubscription.unsubscribe();
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用异步管道

ngOnInit() {
    this.data$ = this.somethingService.getData();
}
Run Code Online (Sandbox Code Playgroud)

<div *ngFor="let item of data$ | async">
Run Code Online (Sandbox Code Playgroud)

(或类似)

async管道将认购/自动退订