在 Angular 中,页面会对多个操作(例如按钮单击)进行多个 http 调用。但是,当按下最后一个“完成”按钮时,我想确保所有这些请求在进展之前都已完成。我尝试将 forkJoin 与 observables 一起使用,但它会触发请求本身,这不是我想要做的,我想要其他操作来触发请求,只是为了确保异步请求在“DONE”时完成点击。有了 promise ,我只需将 promise 推送到数组,然后执行 Promise.all(allRequests).then(()=>{})
observables: Observable<any>[];
onBtn1Click(){
let o1 = this.service.doAction1();
this.observables.push(o1);
o1.subscribe(resp => {
//do action1
});
}
onBtn2Click(){
let o2 = this.service.doAction2();
this.observables.push(o2);
o2.subscribe(resp => {
//do action2
});
}
onDoneClick(){
// I would like something like this just that it wouldn't trigger the requests but make sure they are completed.
forkJoin(this.observables).subscribe(()=>{
//Proceed with other things
});
}
最佳答案
除非有人想出一种优雅的方法,否则应该采用以下方法。
我正在创建一个对象来保存来自 HTTP 请求的每个冷可观察值的热可观察值。该请求将使用 RxJS Finalize 运算符发送到其相应的热可观察对象。然后可以使用 forkJoin
与 take(1)
组合这些热可观察量,以等待源请求完成。
private httpReqs: { [key: string]: ReplaySubject<boolean> } = Object.create(null);
onBtn1Click() {
this.httpReqs['btn1'] = new ReplaySubject<boolean>(1);
this.service.doAction1().pipe(
finalize(() => this.httpReqs['btn1'].next(true))
).subscribe(resp => {
// do action1
});
}
onBtn2Click() {
this.httpReqs['btn2'] = new ReplaySubject<boolean>(1);
this.service.doAction1().pipe(
finalize(() => this.httpReqs['btn2'].next(true))
).subscribe(resp => {
// do action2
});
}
onDoneClick(){
forkJoin(
Object.values(this.httpReqs).map(repSub =>
repSub.asObservable().pipe(
take(1)
)
)
).subscribe(() => {
// Proceed with other things
});
}
关于javascript - Angular 等待所有订阅完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65627291/