首页 > 解决方案 > 使用 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>

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

标签: rxjs

解决方案


你正在使用concatMap(). 这会发出从主体发出的第一个可观察对象发出的所有事件,然后发出由主体发出的第二个可观察对象发出的所有事件。

但是第一个 observable 永远不会完成,所以第二个 observable 不可能发出任何东西。

如果您希望服务返回的 observable 在 2 秒后发出一次然后完成,您只需要

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

推荐阅读