有一个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 发出默认值,但我不需要它
问题在于您未发布的其余代码:
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())
)
)
);