簡體   English   中英

Angular 和 RxJs 結合了兩個 http 請求

[英]Angular and RxJs combine two http requests

我正在發出兩個 http 請求,每個請求都返回一個observable<IProduct>; 我想將兩者組合成一個本地對象並使用異步管道從每個對象中獲取值。

productA$: observable<IProduct>;
productB$: observable<IProduct>;
combinedProds$: ?

this.productA$ = httpCall();
this.productB$ = httpCall();


  this.combinedProds$ = combineLatest([
  this.productA$,
  this.productB$
   ])
  .pipe(
    map(([productA, productB]) =>
      ({ productA, productB}))
  );

我遇到了這個問題,我不知道combinedProds$應該是什么類型。

也許forkJoin是您正在尋找的那個?

forkJoin 最適合 Http 調用,我在處理 http 請求時經常使用它

// RxJS v6.5+
import { ajax } from 'rxjs/ajax';
import { forkJoin } from 'rxjs';

/*
  when all observables complete, provide the last
  emitted value from each as dictionary
*/
forkJoin(
  // as of RxJS 6.5+ we can use a dictionary of sources
  {
    google: ajax.getJSON('https://api.github.com/users/google'),
    microsoft: ajax.getJSON('https://api.github.com/users/microsoft'),
    users: ajax.getJSON('https://api.github.com/users')
  }
)
  // { google: object, microsoft: object, users: array }
  .subscribe(console.log);

更新

forkJoin 返回一個Observable<any>這樣你就可以像這樣改變你的

combinedProds$: Observable<any>

暫無
暫無

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

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