为什么不是所有流都在 combineLatest 中发出值?

问题描述 投票:0回答:1

有一个combine最新算子:

this.result$ = combineLatest([
      this.data$.pipe(tap(() => console.log('data'))),
      this.sourceWithImage$.pipe(tap(() => console.log('image'))),
      this.sourceWithFields$.pipe(tap(() => console.log('fields'))),
    ]).pipe(
      map(([data, image, fields]) => {
        return { data, image, fields };
      })
    );

为什么不是所有的流都发出值?只有数据。 link

的 Stackblitz 示例

我尝试使用 startWith 发出默认值,但我不需要它

angular rxjs
1个回答
0
投票

问题在于您未发布的其余代码:

    this.sourceWithImage$ = this.data$.pipe(
      switchMap(() =>
        of().pipe(
          delay(5000),
          map(() => new Date().valueOf())
        )
      )
    );

    this.sourceWithFields$ = this.data$.pipe(
      switchMap(() =>
        of().pipe(
          delay(3000),
          map(() => new Date().valueOf())
        )
      )
    );

this.sourceWithImage$
this.sourceWithFields$
中,您在 switchMap 中有一个空的
of()
调用。
of()
运算符创建一个可观察对象,它发出传递给它的参数。由于您没有传递任何参数,它会创建一个立即完成而不会发出任何值的可观察对象。这会导致后续的
delay()
map()
运算符无效。

要解决此问题,您可以修改

of()
调用以传递如下值:

this.sourceWithImage$ = this.data$.pipe(
  switchMap(() =>
    of(null).pipe( // Pass a value to of()
      delay(5000),
      map(() => new Date().valueOf())
    )
  )
);

this.sourceWithFields$ = this.data$.pipe(
  switchMap(() =>
    of(null).pipe( // Pass a value to of()
      delay(3000),
      map(() => new Date().valueOf())
    )
  )
);

在这里更新了 Stackblitz.

© www.soinside.com 2019 - 2024. All rights reserved.