Angular和RxJ结合了两个http请求

chr*_*dev 2 javascript rxjs typescript angular

我正在执行两个http请求,每个请求都返回a 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}))
  );
Run Code Online (Sandbox Code Playgroud)

我遇到的这个问题,我不知道combinedProds$应该是哪种类型。

Ton*_*Ngo 5

也许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);
Run Code Online (Sandbox Code Playgroud)

更新资料

forkJoin返回一个,Observable<any>这样您可以更改您的

combinedProds$: Observable<any>