Search code examples
ngrxeffect

NGRX: from @Effect to createEffect


I have update my Angular app and now I need to convert some code. What is the translation from @Effect to createEffect for the following code, please?

@Effect()
getTasks$ = this.actions$.pipe(
    ofType(taskActions.LOAD_ACCOUNTS_TASKS),
    switchMap(() => {
        return this.rest.get(`${tasksUrl}`).pipe(
            map((response) => new taskActions.LoadTasksSuccess(response)),
            catchError((err: HttpErrorResponse) => of(err.status === 401 ?
                new oauthActions.FailedRequestWith401(new taskActions.LoadTasks()) :
                new taskActions.LoadTasksFail()
            ))
        );
    })
);

Solution

  • There is not much mystery to it, you just wrap it actions observable in a createEffect factory function:

     getTasks$ = createEffect(() =>
        this.actions$.pipe(
          ofType(taskActions.LOAD_ACCOUNTS_TASKS),
          switchMap(() =>
            this.rest.get(`${tasksUrl}`).pipe(
              map((response) => new taskActions.LoadTasksSuccess(response)),
              catchError((err: HttpErrorResponse) =>
                of(
                  err.status === 401
                    ? new oauthActions.FailedRequestWith401(new taskActions.LoadTasks())
                    : new taskActions.LoadTasksFail()
                )
              )
            )
          )
        )
      );