gpt4 book ai didi

angular - 尝试使用已损坏的 View : detectChanges event though the view is detached

转载 作者:行者123 更新时间:2023-12-03 23:52:09 27 4
gpt4 key购买 nike

我有一个组件可以进行一些服务调用并获得 promise 。 promise 解决后,我正在做检测更改。但是有时当组件 View 已经被销毁时, promise 会被解决,例如用户关闭的选项卡(我们应用程序的内部选项卡)。在那种情况下,我得到ViewDestroyedError: Attempt to use a destroyed view: detectChanges .即使我已经分离了我的 tab.component 的销毁阶段的 View 。我的问题是我在这里做错了什么?

我试图将 View 从销毁阶段的更改检测中分离出来,但没有运气,在销毁阶段后 promise 正在解决,并且仍然调用 detectChanges。我确实理解 ngOnDestroy 实际上并没有销毁该类,并且其中的代码将在垃圾收集阶段被销毁。

这是我的 tab.component 中导致问题的示例代码

const promises:Promise<any>[] = [];
_.each(types, (type:string) => {
promises.push(this.service.getResultsBy(type))
})
Promise.all(promises)
.then((data) => {
//some code here
this.cd.detectChanges();
})

ngOnDestroy我正在从 CD 中分离 View
ngOnDestroy() {
this.cd.detach();
}

在这种情况下, promise 对我来说很重要,因为即使组件被破坏,我也确实需要进行一些计算/状态保存。我只是想了解如何将 View 分离得足够好,以使我在 promise 中的代码不会导致更改检测尝试。

最佳答案

ngOnDestroy 上的变更检测中分离不需要,也不会帮助解决此错误。但是,您不能调用 detectChangesngOnDestroy 之后已被调用。使用 observables,您可以取消订阅 ngOnDestroy 中的 observable。 .无法取消订阅 Promise所以你需要在你的组件中保留一个标志。

export class MyComponent {

private destroyed = false;

ngOnDestroy() {
this.destroyed = true;
}

triggerChangeDetection() {
if (!this.destroyed) {
this.cd.detectChanges();
}
}

}

关于angular - 尝试使用已损坏的 View : detectChanges event though the view is detached,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56056911/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com