首页 > 解决方案 > 如何将 Observable 标识符传递给 mergeMap

问题描述

有一个各种类型的 observables 列表,我想使用 mergeMap 监视它们的输出。使用此示例代码可以清楚地看到该部分:

export class TestClass {

  test() {

    const observableA = of(1, 2, 3);
    const observableB = of(7, 3, 6);
    const observableC = of('A', 'B', 'C');
    const observableD = of(true, true, false);
    const observableE = of(false, true, false);
    // etc...

    const observablesList = [
      observableA,
      observableB,
      observableC,
      observableD,
      observableE
    ]

    from(observablesList).pipe(
      mergeMap(o => o)
    ).subscribe(v => this.handleValue(v));

  }
  private handleValue(val) {
    console.log(val);
  }

在这里,我们得到了列出的所有值的良好输出:1、2、3、7、3、6、A、B、C、true、true、false、false、true、false

问题是如何将数组索引或 Observable 的标识符传递给函数handleValue(val)以便它可以这样写:

  private handleValue(val, index: number) {
    console.log(index, ' - ', val);
  }

并会得到类似这样的输出:

0 - 1, 0 - 2, 0 - 3,

1 - 7, 1 - 3, 1 - 6,

2 - A,2 - B,2 - C,

3 - 真,3 - 真,3 - 假,

4 - 假,4 - 真,4 - 假

或者:

  const observablesListB: {[name: string]: Observable<any>}[] =
  [
      {'obsA': observableA},
      {'obsB': observableB},
      {'obsC': observableC},
      {'obsD': observableD},
      {'obsE': observableE}
  ];


  from(observablesList).pipe(
    mergeMap(o => o)
  ).subscribe(v => this.handleValue(v, name));

  private handleValue(val, name: string) {
    console.log(name, ' - ', val);
  }

并会得到类似这样的输出:

'obsA' - 1,'obsA' - 2,'obsA' - 3,

'obsB' - 7,'obsB' - 3,'obsB' - 6,

'obsC' - A,'obsC' - B,'obsC' - C,

'obsD' - 真,'obsD' - 真,'obsD' - 假,

'obsE' - 假,'obsE' - 真,'obsE' - 假

我不清楚如何在以下部分引用索引(或 Observable 的 id):

mergeMap(o => ...)

或者

.subscribe( ... 

或者任何正确的语法应该是

标签: angularrxjsobservable

解决方案


基于官方文档https://rxjs.dev/api/operators/mergeMap 第二个参数是索引

mergeMap<T, R, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector?: number | ((outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R), concurrent: number = Number.POSITIVE_INFINITY): OperatorFunction<T, ObservedValueOf<O> | R>

它返回观察值。

因此,鉴于我们可以这样做来实现您正在寻找的结果:

from(observablesList).pipe(
  mergeMap((o,i) => o.pipe(map((obj, index) => ({index: i, obj})))),
).subscribe(v => this.handleValue(v));

private handleValue(val) {
  console.log(val.index, ' - ', val.obj);
}

Stackblitz:https ://stackblitz.com/edit/rxjs-q379af


推荐阅读