0

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

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

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

现在我通过创建一个 BehaviorSubject 计数器来做到这一点,并且在每次请求时我都会增加它。当这个计数器达到某个值时,我会更改loadingfalse并显示一个表格。有没有更好的办法?

看起来像

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()在它们周围使用,但我认为这是不对的。

4

2 回答 2

1

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

 forkJoin([...requests])
   .subscribe(_ => this.loading = false;) 
于 2019-02-20T14:25:05.657 回答
-1

请使用 RxJs 的 forkjoin

Plunker 演示链接

 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;
    });
  }

参考:

于 2019-02-20T14:31:28.477 回答