是否需要从Observable
退订Angular HttpClient
的方法返回的订阅?
例如:
this.http.get(url).subscribe(x => this.doSomething());
我需要取消订阅吗?我问这是因为我不知道Angular是否自行处理。另外,请求是一次性的,不是连续的。我倾向于认为我不需要。你有什么想法?
根据以下帖子: Angular/RxJs When should I unsubscribe from `Subscription`
RxJS处理一次性订阅,但我没有在他们的文档中找到任何内容。
答案 0 :(得分:0)
有两种处理方法:
1)是的,如果您在ts文件中正常订阅了observable,则必须手动退订。 通常我们可以在ngOnDestroy()生命周期方法中取消订阅
2)如果在angular模板中的observable上使用异步管道语法,则它将自动关闭订阅
observable | async
答案 1 :(得分:0)
答案 2 :(得分:0)
这是我的工作:
export class CustomerSummaryComponent implements OnInit, OnDestroy {
subscriptions: Subscription[];
ngOnInit() {
this.subscriptions = [];
this.subscriptions.push(
this.customerService.getCustomer(this.customerId).subscribe(
data => {
},
error => {
console.log(error);
}
)
);
}
ngOnDestroy() {
for (const x of this.subscriptions) {
x.unsubscribe();
}
}
}
答案 3 :(得分:0)
当您使用ngOnDestroy离开页面时,可以在“相同”时间取消订阅页面中的所有Observable。您通过管道传递一个Observable,该Observable在离开页面并关闭功能时会被激活。
export class X implements OnInit, OnDestroy {
private unsubscribe$ = new Subject();
ngOnInit() {
this.functionOne();
}
ngOnDestroy() {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
functionOne() {
this.service
.getData()
.pipe(takeUntil(this.unsubscribe$))
.subscribe(
(result) => {},
(error) => {}
);
}
}