我们有很多组件发出http请求来获取它们的数据。当组件被销毁时,我的任务是取消http请求。所以我能做的就是进入每个单独的组件,实现ngOnDestroy()
,并将http订阅存储为组件的类的成员,但是我们有太多的组件,我无法逐一完成。
有没有办法告诉angular,当任何组件被销毁时,取消它所有的http请求?
发布于 2018-12-14 05:00:42
另一个选择是定义一个更好的订阅模式,这样你就不需要取消订阅了。
例如,您可以这样做:
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的。)
https://stackoverflow.com/questions/53769406
复制相似问题