简体   繁体   English

Angular 和 RxJs 结合了两个 http 请求

[英]Angular and RxJs combine two http requests

I am making two http requests, each return a observable<IProduct>;我正在发出两个 http 请求,每个请求都返回一个observable<IProduct>; and I want to combine both into a local object and use the async pipe to bring values from each.我想将两者组合成一个本地对象并使用异步管道从每个对象中获取值。

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

This issue I'm getting, I don't know what type combinedProds$ should be.我遇到了这个问题,我不知道combinedProds$应该是什么类型。

Maybe forkJoin is the one you are looking for ?也许forkJoin是您正在寻找的那个?

forkJoin work best with Http call and I'm using it a lot when dealing with http request 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);

Update更新

forkJoin return an Observable<any> so you can change your like this forkJoin 返回一个Observable<any>这样你就可以像这样改变你的

combinedProds$: Observable<any>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM