angular - 取消订阅 Rxjs Observables
问题描述
我开始使用一个使用 Rxjs observables 的遗留 angular 6 应用程序。组件中的可观察对象似乎没有使用我所看到的取消订阅。ngOnInit 中的订阅示例:
this.service.getCustomerDetail(customers).subscribe(
(data) => {
this.customerData = data;
},
() => {
this.notify.addNotification(
new notification(
`Error retrieving customer data`
)
);
}
);
订阅者正在使用完成,即使其中没有任何内容,即 Rxjs 订阅的 Next、Error、Complete 值,但在我看来,它需要将这些推送到订阅中,然后在 ngOnDestroy 上取消订阅所有这些。即使完整在可观察范围内,这些没有取消订阅的订阅也会留在堆内存中,也就是导致内存泄漏,这是正确的吗?
在我的订阅使用错误和完整部分的情况下,我会使用 TakeUntil 方法,例如:
this.service.getCustomerDetail(customers)
.pipe(takeUntil(this.ngUnsubscribe))
.subscribe(
(data) => {
this.customerData = data;
},
() => {
//error section
this.notify.addNotification(
new notification(
`Error retrieving customer data`
)
);
},
() => {
//complete section
this.loadAddlDetail();
}
);
感谢您提供有关此的任何信息。
解决方案
有两种方法可以做到这一点。如果这是一个孤立的案例,以下就足够了
方法 1 - 如果这是一个孤立的案例
-------------------------------------------------- -
在班上
更改类声明以包括OnDestroy
export class AppComponent implements OnInit, OnDestroy
添加私有变量来存储订阅
private serviceSubscription = null
在 ngOnInit
this.serviceSubscription = this.service.getCustomerDetail(customers).subscribe(
(data) => {
this.customerData = data;
},
() => {
this.notify.addNotification(
new notification(
`Error retrieving customer data`
)
);
}
);
实施 OnDestroy
ngOnDestroy() {
if (this.serviceSubscription != null) {
this.serviceSubscription.unsubscribe()
}
}
-------------------------------------------------- --------
方法 2 - 如果在多个地方看到这种情况
-------------------------------------------------- --------
为组件创建基类component-base.ts
import { Subscription } from 'rxjs';
import { OnDestroy } from '@angular/core';
export class ComponentBase implements OnDestroy {
private subscriptions: Subscription[] = [];
protected rxs(s: Subscription): void {
this.subscriptions.push(s);
}
ngOnDestroy() {
this.subscriptions.forEach(x => x.unsubscribe());
}
}
将组件从ComponentBase
export class AppComponent extends ComponentBase implements OnInit
在 ngOnInit
ngOnInit() {
this.rxs(this.service.getCustomerDetail(customers).subscribe(
(data) => {
this.customerData = data;
},
() => {
this.notify.addNotification(
new notification(
`Error retrieving customer data`
)
);
}
));
}
推荐阅读
- excel - VBA返回动态数组并分配给变量
- android - 如何防止手机屏幕在使用 ADB 调用 Android pie (9) 时关闭(或不使用,如果可能)
- python - 在散点图上绘制折线图
- python - Don't understand cause of this AttributeError: '_Screen' object has no attribute 'setimage'
- javascript - 如何用两个对象读取 Json?
- python - 检查python中是否存在系统范围内的互斥锁
- c++ - 如何限制我连续拥有的数字数量?
- java - 如何创建弹出消息以提醒用户字段不完整?
- java - 如何使用比较器
作为通用 SortedDoublyLinkedList 中的参数 - java - 如果鼠标正在移动,则重新启动计时器