简体   繁体   中英

Angular and RxJs combine two http requests

I am making two http requests, each return a 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.

Maybe forkJoin is the one you are looking for ?

forkJoin work best with Http call and I'm using it a lot when dealing with http request

// 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

combinedProds$: Observable<any>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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