英文:
Why not all streams are emit value in combineLatest?
问题
这里有一个combineLatest
操作符:
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 };
})
);
为什么不是所有的流都发出值?只有data
发出值。在这个链接中有一个 Stackblitz 示例。
我已经尝试使用startWith
来发出默认值,但我不需要它。
英文:
There is a combineLatest operator:
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 };
})
);
Whydo not all streams emit values? Only data. Stackblitz exmaple by link
I have tried to emit default values using startWith, but I dont need it
答案1
得分: 0
以下是代码的中文翻译部分:
在this.sourceWithImage$
和this.sourceWithFields$
两者中,您在switchMap
中都有一个空的of()
调用。of()
操作符创建一个可观察对象,会发出传递给它的参数。由于您没有传递任何参数,它会立即创建一个可观察对象,而不发出任何值,这导致随后的delay()
和map()
操作没有效果。
要解决这个问题,您可以修改of()
调用以传递一个值,如下所示:
this.sourceWithImage$ = this.data$.pipe(
switchMap(() =>
of(null).pipe( // 传递一个值给of()
delay(5000),
map(() => new Date().valueOf())
)
)
);
this.sourceWithFields$ = this.data$.pipe(
switchMap(() =>
of(null).pipe( // 传递一个值给of()
delay(3000),
map(() => new Date().valueOf())
)
)
);
英文:
The issue is with the rest of the code you didn't post:
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())
)
)
);
In both this.sourceWithImage$
and this.sourceWithFields$
, you have an empty of()
call in the switchMap. The of()
operator creates an observable that emits the arguments passed to it. Since you didn't pass any arguments, it creates an observable that completes immediately without emitting any values. This causes the subsequent delay()
and map()
operators to have no effect.
To fix this issue, you can modify the of()
calls to pass a value like this:
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())
)
)
);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论