如何对可观察对象使用 OR?

How to use OR for observables?

我有两个可观察值:

this.one$ = this.httpClient.get<any>();
this.tow$ = this.httpClient.get<any>();

我需要根据条件获得第三个可观察结果:

if (url == "one) {
    this.result$ = this.one$;
} else if (url == "two") {
    this.result$ = this.two$;
}

在模板中使用:

{{ result | async }}

如何使用 Rxjs 更优雅地做到这一点?

您可以使用 RxJS iif 条件函数。尝试以下

import { iif } from 'rxjs';

this.result$ = iif(() => url === "one", this.one$, this.two$);

来自文档:

Decides at subscription time which Observable will actually be subscribed.

因此,如果您要在控制器中订阅(而不是使用 async 管道),您可以在订阅前动态更改条件。

url: string;
this.result$ = iif(() => url === "one", this.one$, this.two$);

url = 'one';
this.result$.subscribe(...);      // <-- this.one$;

url = 'two'
this.result$.subscribe(...);      // <-- this.two$;

对于你的问题,我看到了两种不同的解决方案:

第一个正在压缩它们,return 其中一个在 pipe:

const url = 'one';
const first$ = of('one');
const two$ = of('two');

zip(first, two).pipe(
  map(data => {
    if(url === 'one') {
      return data[0];
    } else {
      return data[1];
    }
  })
).subscribe(e => console.log(e))

这不是您问题的最佳解决方案,但有时会很有用。

否则,你可以使用iif,你可以这样使用:

result$ = iif(() => url === "one", one$, two$);