rxjs的iif操作符支持多个条件。

huangapple go评论64阅读模式
英文:

rxjs iif operator with multiple conditions

问题

这是我目前的代码设置:

iif(
    () => !this.id,
    this.service.listStuff$(),
    this.service.listStuffById$(this.id)
).pipe(
    switchMap((list: List) => {
        // ...
    })
).subscribe();

我想根据另一个条件 this.name 来添加条件,如下所示:

if (this.id) {
    return this.service.listStuffById$(this.id)
} else if (this.name) {
    return this.service.listStuffByName$(this.name)
} else {
    return this.service.listStuff$()
}

最好的解决方案是否是链式使用两个 iif

英文:

What is the best way to return Observables based on multiple conditions?

This is how my code is set up right now:

iif(
    () => !this.id,
    this.service.listStuff$(),
    this.service.listStuffById$(this.id)
).pipe(
    switchMap((list: List) => {
        // ...
    })
).subscribe();

I want to add another condition this.name such that

if (this.id) {
    return this.service.listStuffById$(this.id)
} else if (this.name) {
    return this.service.listStuffByName$(this.name)
} else {
    return this.service.listStuff$()
}

Would the best solution be to chain two iifs?

答案1

得分: 2

你可以随时嵌套 iif 调用,因为 ObserveableInput 类型也是 Observable

英文:

You can always nest the iif calls, since ObserveableInput types are also Observables.

iif(
    () => this.id,
    // if (this.id) {
    this.service.listStuffById$(this.id),
    iff(
        () => this.name,
        // } else if (this.name) {
        this.service.listStuffByName$(this.name),
        // } else {
        this.service.listStuff$()
        // }
    )
).pipe(
    switchMap((list: List) => {
        ...  
    }),
).subscribe();

huangapple
  • 本文由 发表于 2023年6月13日 08:33:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76461043.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定