比较来自两个 Observable 的值和 return 个 Observable

Compare values from two Observables and return an Observable

我正在检查条件并得到 Observable<boolean>:

let result = this.service.getCity().pipe(
  map((city: string) => city && city.toLowerCase() === ???) 
);

我需要检查 city 是否等于:

this.authenticationService.getCity():

这个方法还有returns和Observable<boolean>.

如何组合两个可观察值并在条件中使用这两个值?

我需要 return 最后一个 Observable。

假设 this.service.getCity()this.authenticationService.getCity() returns 单数 object/string 根据您的命名方式。

您可以使用 forkJoin 运算符。这是一个例子

const source1 = of("CityName");
const source2 = of("CityName");

forkJoin({
  source1,
  source2
}).pipe(
  map((x: {source1, source2}) => x.source1 === x.source2)
).subscribe(result => console.log(result));

StackBlitz:https://stackblitz.com/edit/rxjs-luncbd

forkjoin的替代方法

如果 observable completion 不是比较两个 observable 的触发器,您可以使用 switchMap

const { from, of } = rxjs;
const { map, switchMap, tap, take } = rxjs.operators;

const serviceCity$ = () => from(['Berlin', 'London', 'Paris']);
const authentificationCity$ = () => of('london');

const result$ = serviceCity$().pipe(
  map(city => city && city.toLowerCase()),
  switchMap(city => authentificationCity$().pipe(
    map(authCity => city === authCity),
    take(1),
  ))
);

result$.subscribe(v => console.log('authentification city equals london: ', v));
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.3/rxjs.umd.min.js"></script>

信息

  • serviceCity$authentificationCity$ 等于你的 service.getCity()this.authenticationService.getCity()
  • 我假定两个函数 return 和 string 并且您想比较两者 strings。如果您想比较两个 pre-mapped 值,请向我解释,我会更新代码。
  • result$ 将在 serviceCity$ 发射后触发 authentificationCity$
  • take(1) 避免 result$authentificationCity$ 而不是 serviceCity$
  • 触发