如何解决在foreach方法中运行可观察对象时无法取消订阅
我正在通过foreach方法迭代一组项目。每个项目执行两个嵌套的http调用。循环结束后,我无法取消订阅可观察对象。您能否为此提供解决方案
import { Observable,Subject } from 'rxjs';
import { mergeMap,take } from 'rxjs/operators';
private _unsubscribeAll: Subject<any>;
constructor(...) {
this._unsubscribeAll = new Subject();
}
ngOnChanges(): void {
//this.fileList is an array of ids
this.fileList.forEach((id) => {
this.getData(id).subscribe((res:any) => {
console.log(res)
})
});
getData(id): Observable<any> {
return this.fileService.getFileDetails(id).pipe(take(1),mergeMap(data => {
if(data != undefined) {
return this.fileService.downloadFile(data[0].path)
}
}))
}
}
ngOnDestroy() {
this._unsubscribeAll.next();
this._unsubscribeAll.complete();
}
解决方法
您可以这样简单:
const subscriptions: Subscription[] = []
this.fileList.forEach((id) => {
this.subscriptions.push(
this.getData(id).subscribe((res: any) => {
console.log(res)
})
)
});
ngOnDestroy() {
this.subscriptions.forEach(s => s.unsubscribe())
}
,
考虑通过将fileList
映射到可观察对象数组并使用forkJoin
等待它们全部完成来创建单个订阅,如下所示:
private subscription: Subscription;
public ngOnChanges(): void {
this.subscription = this.getData().subscribe((x:any[]) => { });
}
public getData(): Observable<any[]> {
const observables: Observable<any>[] = this.fileList.map(id => {
return this.fileService.getFileDetails(id).pipe(
first(),filter(data => data != undefined),mergeMap(data => this.fileService.downloadFile(data[0].path))
)
);
return forkJoin(observables);
}
public ngOnDestroy(): void {
this.subscription.unsubscribe();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。