rxjs - 使用 Subject next() 调用 observables 不起作用
问题描述
为什么这个功能只工作一次?我单击一个按钮来调用 Subject 队列上的 next() ,但如果我单击另一个按钮它不起作用。
getData(text): Observable<string> {
const timer$ = timer(2000);
const observable = new Observable<string>(observer => {
timer$.pipe(
map(() => {
observer.next('http response ' + text);
})
).subscribe();
});
return observable;
}
我设置了一个 Subject 并使用 next() 应该使 observable 发出数据。
queue = new Subject();
streamA$: Observable<string>;
streamB$: Observable<string>;
images$: Observable<string>;
constructor(private timerService: TimerService) {
}
ngOnInit() {
this.streamA$ = this.timerService.getData('a');
this.streamB$ = this.timerService.getData('b');
this.images$ = this.queue.pipe(concatMap((data: string) => data));
}
clickA() {
this.queue.next(this.streamA$);
}
clickB() {
this.queue.next(this.streamB$);
}
模板:
<button (click)="clickA()">Click A</button>
<button (click)="clickB()">Click B</button>
<div>{{images$ | async}}</div>
解决方案
你正在使用concatMap()
. 这会发出从主体发出的第一个可观察对象发出的所有事件,然后发出由主体发出的第二个可观察对象发出的所有事件。
但是第一个 observable 永远不会完成,所以第二个 observable 不可能发出任何东西。
如果您希望服务返回的 observable 在 2 秒后发出一次然后完成,您只需要
return timer(2000).pipe(
map(() => 'http response ' + text)
);
推荐阅读
- gradle - Gradle:在任务中获取任务命令行参数
- python - 如何根据给定值迭代函数一定次数
- json - pmudt_50005:[错误] 处理数据失败:找不到 RepeatingGroup
- ios - 我可以为我的 iOS 应用程序提供多个 url 方案吗?
- react-native - React Native Flat List 自定义网格
- laravel - Vue JS 获取每个单选组的值
- ios - 让 Button 动作覆盖它的 superview swiftUI
- python - Dash : 从另一个回调中调用一个回调
- mongodb - 如何捆绑 MONGODB?
- rest - DocuSign API:是否可以按文档字段的值过滤信封?