Search code examples
rxjsngrxngrx-effectsfork-joinrxjs6

RxJs 6 - Make 2 http calls and wait for all responses


@Effect()    
initDomain$: Observable<Action> = this.actions$.pipe(
  ofType('INIT_DOMAIN'),
  mergeMap((action: any) =>
     this.http.get('https://demo.api/url1.php').pipe(
        switchMap((data) => [
           {type: 'INIT_IT', payload: data}
        ]),
        catchError(() => of({type: 'INIT_IT_FAILED'}))
     )
  )
);

I have this angular effect (ngrx) that makes 1 request before continue. How can I make 2 requests and wait for both responses before continue? I know that forkJoin() is the answer but I'm little confused about the syntax


Solution

  • forkJoin(
     this.http.get('myUrl'),
     this.http.get('myOtherUrl')
    )
    

    OR if you have a bundle of observables in an array you could also write

    const myArrayOfObservables = [
      this.http.get('myUrl'),
      this.http.get('myOtherUrl')
    ];
    
    forkJoin(
      myArrayOfObservables
    )
    

    This is because "forkJoin" uses the "spread" (...args) operator for its params.