5

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.

1
  • 1
    Define an interface called, may-be IProductPair and map to that type. Commented Aug 20, 2019 at 14:45

1 Answer 1

9

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>

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the reply, the issue I'm getting, what type should the combinedProds$ variable be?
observable<any> works, but I'd have thought something like observable<IProduct[]> would work here too, if I wanted to 'strongly type' it?
Yes I understand but the forkJoin return an array of Observable
This works :) If I get the type solved, I will post an update here. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.