【发布时间】:2021-12-17 09:11:03
【问题描述】:
我想进行 3 个返回布尔值的 http 调用。
我想要的是只有在上一次调用的结果是true时才进行下一次调用
IE:call1() -> 如果false,停止,如果true:call2() -> 如果false,停止,如果true:
@987654329 @
现在以指示返回 false 的调用的方式读取结果。
我第一次尝试使用 switchMap:
this.call1()
.pipe(
switchMap((r1) => (r1 ? this.call2() : of(false))),
switchMap((r2) => (r2 ? this.call3() : of(false)))
)
.subscribe((r) => {
console.log('inside subscribe:', r);
});
现在在订阅中我得到的问题是:'inside subscribe:' false
而且我不知道错误结果是来自 call1,2 还是 3。
所以我的解决方案是将结果保存在外部数组中,如下所示:
// seriel execution with switchMap, we can use each result to the next call
// + save all results
const results = [false, false, false];
this.call1()
.pipe(
// save stage1 result
tap(r1 => results[0] = r1),
// if true, make call2, else return false
switchMap((r1) => (r1 ? this.call2() : of(false))),
// save stage2 result
tap(r2 => results[1] = r2),
// if true, make call3, else return false
switchMap((r2) => (r2 ? this.call3() : of(false))),
// save stage3 result
tap(r3 => results[2] = r3),
)
.subscribe((r) => {
console.log('inside subscribe:', r); // r is the latest value results[2]
console.log('all results:', results) // array of all stages [true,false,false]
});
}
它似乎有效,但也许还有另一种无需外部工作的方法?仅使用 rxjs 运算符?
StackBlitz 链接:
https://stackblitz.com/edit/angular-rxjs-playground-zjnh7u?devtoolsheight=33&file=app/app.component.ts
【问题讨论】:
-
为什么返回值很重要?