【问题标题】:Invoking observables with Subject next() not working使用 Subject next() 调用 observables 不起作用
【发布时间】:2019-08-16 08:42:28
【问题描述】:

为什么这个功能只能工作一次?我单击一个按钮来调用主题队列上的 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 observable 以便测试操作符

标签: rxjs


【解决方案1】:

您正在使用concatMap()。这会发出从主体发出的第一个 observable 发出的所有事件,然后发出由主体发出的第二个 observable 发出的所有事件。

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

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

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

【讨论】:

  • 好的,因为我没有在 observable 创建中使用 complete()
猜你喜欢
  • 2018-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-28
  • 2017-03-18
  • 1970-01-01
  • 2016-02-07
  • 2020-08-22
相关资源
最近更新 更多