Search code examples
angularangular-routingngrxngrx-store

Dispatch action on Angular router change


I'm using Ngrx in Angular 8 app, and I want to dispatch an action when user closing the router. What options do I have? Do I have to create the new Guard and implement CanDeactivate method from the router, or I can do it without any additional services, straight from my component? Thanks for any tips or examples


Solution

  • Since you're using NgRx I suggest listening to the router effects within the module that needs to perform the action.

    On that specific router event you can dispatch your action.

    Router events: https://angular.io/api/router/Event

    Example effect:

    routerEvents$ = createEffect(() => {
        return this.router.events.pipe(
            filter((event) => {
                return event instanceof <event> // replace with your router event
            }),
            mergeMap(() => {
                // do some stuff
            })
        );
    });
    
    constructor(
        private router: Router
    ) {}