Search code examples
angulartypescriptngrx

NgrX effect redirect angular


I have effect like this

  createAssignment$ = createEffect(() =>
    this.action$.pipe(
      ofType(AssignmentActions.createAssignment),
      switchMap((action) =>
        this.assignmentService.createNewAssignment(action.assignmentTo).pipe(
          map((data) => AssignmentActions.createAssignmentSuccess({ createdAssignment: data }),
            catchError((error) => of(error))),
        )
      )
    ));

What I need is to redirect user to new page based on value from data, something like this

 this.router.navigate(data);

But I dont know when to do that, to make new effects or just under action? Anyone got similar problem?


Solution

  • You can do that by using the tap operator after map, which will be invoked only if the operation succeeded:

    createAssignment$ = createEffect(() =>
        this.action$.pipe(
            ofType(AssignmentActions.createAssignment),
            switchMap((action) =>
                this.assignmentService
                    .createNewAssignment(action.assignmentTo)
                    .pipe(catchError((error) => of(error)))
            ),
            map((data) => AssignmentActions.createAssignmentSuccess({ createdAssignment: data })),
            tap((data) => { this.router.navigate(data); })
        )
    );