【问题标题】:Why does detectChanges method cause "Attempt to use a destroyed view" Error?为什么 detectChanges 方法会导致“尝试使用已破坏的视图”错误?
【发布时间】: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


【解决方案1】:

无需拨打detectChanges

如果你仍然想使用它,你也可以确保 observable 在销毁时取消订阅。

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

ngOnDestroy() {
  this.serviceSubscription.unsubscribe();
}

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

ngOnInit() {
    this.data$ = this.somethingService.getData();
}

<div *ngFor="let item of data$ | async">

(或类似的)

async 管道将自动订阅/取消订阅

【讨论】:

  • 我正在使用detectChanges 来运行此组件的更改检测,因为此组件目前正在使用OnPush。而且我发现无论unsubscribe 的实现如何,错误都会不断出现。如果我尝试if (!this.changeDetector['destroyed']) { 条件,错误不会再出现,但我不知道detactChanges 有什么问题
  • 很奇怪。我希望取消订阅来解决它。你可以使用如图所示的|async 管道吗? (修复了我代码中的一些问题)
  • 我需要用实际代码中的订阅数据处理一些事情,所以恐怕我无法应用异步管道:(不过感谢您的帮助。
  • 我假设您知道您可以使用.map(...) 来修改到达的数据(而不是subscribe())。
  • 您能在stackblitz.com 中复制吗?这将使调查和尝试变得更容易。
猜你喜欢
  • 1970-01-01
  • 2017-10-23
  • 2023-03-14
  • 2016-10-17
  • 1970-01-01
  • 2017-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多