Search code examples
angularngrxeffects

NGRX Effect sequence dependent api calls


I'm currently working on a feature for an Angular app using NGRX in which an action is dispatched to fetch some data using an Id; then using the response object from the first service call, a second request is made to pull some more details out of a different endpoint. After everything is done data/actions can continue flowing.

The problem: I'm looking for a way to perform the actions described above in a single effect, without chaining effects/actions as that would cause the component rendered to be incomplete.

I've seen some examples using forkJoin but not sure if this would apply as they are not parallel calls but sequenced.

Code is something like this:

    this.actions$.pipe(
      ofType(fetchAllData),
      switchMap(action => {
        const one = this.api.getById(serviceUrl, action.Id);
        return one.pipe(
          switchMap((data) => {
            cons two = this.api.getMoreDetail(serviceUrl, two.id)
            return fetchDataActions(data, []);
          })
        );
      })
    )
  );  

So ideally data would contain everything I need and ready to populate my component.

Notes: - code above does not work - calls have to happen in order as response from call #1 will use as parameter for call #2 - making sequenced dispatched actions does not work as component data is incomplete when rendered.


Solution

  • After the switchMap, you can add a second mapping operator to make the second request.

    I'm looking for a way to perform the actions described above in a single effect, without chaining effects/actions as that would cause the component rendered to be incomplete

    This is incorrect, if an effect doesn't dispatch an action that is handled by a reducer and causing a state change, the component will not be rerendered. It will only rerender if the state would change.

    See the following article where some effect patterns are explained: https://blog.nrwl.io/ngrx-patterns-and-techniques-f46126e2b1e5