Somjit
Somjit

Reputation: 2772

ngrx - effects chaining with error handling : fetch data from second api if first api fetch was successful

I saw some of the SO answers, and this medium post as well, but these still don't solve my current problem.

Scenario:

  1. Add a product.
  2. If successful, get list of all products.

Each of these two cases can have errors:

  1. Business Errors, containing business specific error messages
  2. Network errors, generic stuff like 40x error codes etc

Currently, i have the effect that will use a service to add a product, and dispatch an action based on the success of failure of the operation. This will update the store with the currentProduct being set to the added product.

  @Effect()
  addProduct$: Observable<Action> = this.actions$.pipe(
    ofType(AddProductAction),
    map((action: AddProductAction) => action.payload),
    switchMap((ProductToAdd: Product) =>
      this.productService.addProduct(ProductToAdd).pipe(
        map(response => {
          if (this.responseContainsBusinessError(response)) {
            return new AddProductBusinessError(response);
          } else { // no business error
            return new AddProductSuccess(response);
          }
        }),
        catchError(err => of(new AddProductFail(err))) // network/http error etc
      )
    )
  );

Can someone please show how to change this code so that i can add the second effect/api call to fetch the list of products from the server ?

Upvotes: 2

Views: 570

Answers (1)

avramz
avramz

Reputation: 441

Just add another @Effect which will trigger on AddProductSuccess.

@Effect()
  listAllProducts$: Observable<Action> = this.actions$.pipe(
    ofType(AddProductSuccess),
    ....

Upvotes: 4

Related Questions