Search code examples
angulartypescriptngrxngrx-effects

Chaining two API calls in Angular NGRX Effect


I am trying to resolve a small issue but getting no where with it. I have an effect which gets called with payload. I need to call an API for result and then pass that result and the payload in to another API. What i have tried so far is as follow which is not working as it says the action should return a type.

  @Effect()
  fetchSomething$ = this.actions
    .ofType(fromProfileAction.FETCH_POST)
    .map(action => action)
    .switchMap(payload => Observable.forkJoin([
      Observable.of(payload),
      this.xyzService.getXyz()
    ]))
    .switchMap(data => {
      const [action, xyz] = data;
      return this.postsService
          .abc(action.payload)
          .pipe(
            map(async (response: any) => {
              if (response.res) {
                const result = res.name + " - " + Xyz;
                action.payload.result = result;
              }
              return new fromProfileAction.FetchPostSuccess(action.payload);
            }),
            catchError(err => of(new fromProfileAction.FetchPostFailure({ err })))
          );
    });

Any pointer in right direction.


Solution

  • fetchSomething$ = this.actions
        .ofType(fromProfileAction.FETCH_POST)
        .map(action => action.payload)
        .switchMap(payload => this.xyzService.getXyz(payload)))
        .switchMap(data => {      
          return this.postsService
              .abc(data)
              .pipe(
                map(async (response: any) => {
                  if (response.res) {
                    const result = res.name + " - " + Xyz;
                    action.payload.result = result;
                  }
                  return new fromProfileAction.FetchPostSuccess(action.payload);
                }),
                catchError(err => of(new fromProfileAction.FetchPostFailure({ err })))
              );
        });