使用 Subject next() 调用 observables 不起作用 [英] Invoking observables with Subject next() not working

查看:38
本文介绍了使用 Subject next() 调用 observables 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这个功能只能工作一次?我点击了一个按钮来调用主题队列上的 next() ,它可以工作,但如果我点击另一个按钮,它就不起作用.

Why does this function only work once? I click a button to call the next() on the Subject queue which works but if I click the other button it doesn't work.

  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 发出数据.

I setup a Subject and use next() which should make the observable emit data.

  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

推荐答案

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

You're using concatMap(). This emits all the events emitted from the first observable emitted by the subject, then all the events emitted by the second observable emitted by the subject.

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

But the first observable never completes, so there's no way for the second observable to ever emit anything.

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

If you want the observable returned by the service to emit once after 2 seconds then complete, all you need is

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

这篇关于使用 Subject next() 调用 observables 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆