调用带有主题next()的可观察对象不起作用

时间:2019-08-16 08:42:28

标签: rxjs

为什么此功能只能运行一次?我单击一个按钮以调用“主题”队列上的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(),它应该使可观察的发射数据。

  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>

https://stackblitz.com/edit/angular-subject-queue

1 个答案:

答案 0 :(得分:1)

您正在使用concatMap()。这将发出从对象发出的第一个可观察对象发出的所有事件,然后再发出从对象发出的第二个可观察对象发出的所有事件。

但是第一个可观察对象永远不会完成,因此第二个可观察对象无法发出任何东西。

如果您希望服务返回的可观察对象在2秒后发出一次,然后完成,那么您所要做的就是

return timer(2000).pipe(
  map(() => 'http response ' + text)
);