当任何组件被销毁时,取消订阅/取消所有http请求



我们有很多组件会发出http请求来获取它们的数据。我的任务是在组件被破坏时取消http请求。因此,我可以做的是进入每个单独的组件,实现ngOnDestroy(),并将http订阅存储为组件类的一个成员,但我们有太多的组件,我无法逐一进入并执行这些操作。

有没有一种方法可以告诉angular,当任何组件被破坏时,取消其所有http请求?

另一个选项是定义更好的订阅模式,这样您就不需要取消订阅。

例如,你可以这样做:

export class ProductEditComponent implements OnInit, OnDestroy {
componentActive = true;
ngOnInit(): void {
// Watch for changes to the currently selected product
this.store.pipe(
select(fromProduct.getCurrentProduct),
takeWhile(() => this.componentActive)
).subscribe(
currentProduct => this.displayProduct(currentProduct)
);
ngOnDestroy(): void {
this.componentActive = false;
}
}

注意takeWhile。这样可以确保在组件销毁时停止任何订阅。

您可以在此处找到更多信息:https://brianflove.com/2016/12/11/anguar-2-unsubscribe-observables/(但请注意,本文中显示的代码是针对RxJS的旧版本。(

最新更新