繁体   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