簡體   English   中英

RxJs鏈接可觀察的訂閱

[英]RxJs chaining observables with subscriptions

我有一種形式,其中包含通過調用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() ,但我認為這是不對的。

如果不需要考慮順序,則可以使用rxjs中的forkJoin,其工作方式類似於Promise.all,

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

請使用RxJs的forkjoin

柱塞演示鏈接

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

參考來自:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM