RxJS多个条件调用



我在RxJS中遇到条件调用问题。场景是我在一个forkjoin中有多个HTTP调用。但在调用内部可能存在依赖关系,比如我从第一个调用中得到一个布尔值,如果这是真的,则应该触发第二个调用。这是我现在的代码:
service.method(parameters).pipe(
tap((data: boolean) => {
foo.bar= data;
}),
concatMap(() =>
service
.method(parameters)
.pipe(
tap((data: KeyValue<number, string>[]) => {
if (true) {
foo.foo = data;
}
})
)
)
)

我遇到的问题是,现在总是调用该方法。我的目标是只有当参数为true时才调用该方法,以减少调用量。我希望有人能帮助我。

您可以尝试类似的

service.method(parameters).pipe(
tap((data: boolean) => {
foo.bar= data;
}),
concatMap((data) => data ? // you pass data as parameter and check if true
service  // if data is true you return the Observable returned by the service method
.method(parameters)
.pipe(
tap((data: KeyValue<number, string>[]) => {
if (true) {
foo.foo = data;
}
})
) :
of(false) // if data is false you return an Observable containing what you decide it to contain, in this case 'false' but it could be everything
)
)

其想法是,您第一次调用service.method,将此调用的结果传递给concatMap,然后根据传递给concatMap的参数,决定是再次调用service.method并返回它返回的Observable,还是返回您在concatMap中创建的Observble,包装您想要的任何值。

最新更新