Angular NgRx Create Effect for API Call

    0

    0

    Jose Romero

    Angular TypeScript Recipes

    The code creates an Effect object and passes it into the actions$ pipe. Then, it creates an operator() that takes in an API source and a map function. The map function takes in a data object and returns a FeatureActions.actionSuccess object or FeatureActions.actionFailure object, according to the data's type. Finally, the code creates a catchError function that handles any errors that might occur.

    Library: angular

    Shortcut: angular.ngrx.effect.api

    effectName$ = createEffect(() => {
      return this.actions$.pipe(
          ofType(FeatureActions.action),
          operator(() =>
            apiSource.pipe(
              map(data => FeatureActions.actionSuccess({ data })),
              catchError(error => of(FeatureActions.actionFailure({ error }))))
            ),
      );
    });
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.