【问题标题】:RxJs chaining observables with subscriptionsRxJs 将 observables 与订阅链接起来
【发布时间】:2019-02-20 14:05:39
【问题描述】:

我有一个表单,它由通过调用 API 检索的块组成。

我需要根据该特定调用处理每个调用(我正在基于该调用创建一个 formGroup 部分)。

我想要的是拥有某种全局可观察/状态,当所有调用都进行并处理时,它就会完成。

现在我通过创建一个 BehaviorSubject 计数器来做到这一点,并在每次请求时增加它。当这个计数器达到某个值时,我将loading 更改为false,然后显示一个表单。有没有更好的办法?

看起来像

o1.subscribe(() => {... this.counter.next(this.counter.value + 1) });
o2.subscribe(() => {... this.counter.next(this.counter.value + 1) });
o3.subscribe(() => {... this.counter.next(this.counter.value + 1) });

.

this.counter.subscribe(val => if (val === 3) { this.loading = false; }

我曾想过创建of() 包装器并在它们周围使用concat(),但我认为这是不对的。

【问题讨论】:

  • 如果订单是一个问题,concat 应该可以工作,你为什么认为这是不对的?
  • @ABOS 首先它链接所有方法并按顺序排列它们,同时我可以从同时请求中受益。此外,它是一个可观察的结果,看起来并不正确。
  • 如果顺序不是问题,您可以使用 forkJoin。
  • 谢谢。这对我有用。您可以将其发布为答案,我会标记它。

标签: angular typescript rxjs request-queueing


【解决方案1】:

如果顺序不是问题,您可以使用来自 rxjs 的 forkJoin,其工作方式类似于 Promise.all,

 forkJoin([...requests])
   .subscribe(_ => this.loading = false;) 

【讨论】:

    【解决方案2】:

    请使用 RxJs 的 forkjoin

    Plunker Demo link

     ngOnInit() {
        forkJoin(
          this._myService.makeRequest('Request One', 2000),
          this._myService.makeRequest('Request Two', 1000) 
          this._myService.makeRequest('Request Three', 3000) 
        )
        .subscribe(([res1, res2, res3]) => {
          this.propOne = res1;
          this.propTwo = res2;
          this.propThree = res3;
        });
      }
    

    Ref from :

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-10
      • 2017-03-26
      • 2020-10-28
      • 2017-08-24
      • 1970-01-01
      • 1970-01-01
      • 2021-01-16
      • 2017-12-17
      相关资源
      最近更新 更多