ssougnez
ssougnez

Reputation: 5876

Re-evaluate "canActivate" when condition changes without navigation

I have an angular 4 application with some route guarded by this class:

export class AdminGuard implements CanActivate {
    constructor(private userService: UserService) { }

    canActivate(): boolean {
        return this.userService.isAdministrator();
    }
}

This allows a route to be protected if the user is an administrator. It works very well but there is a logout functionality in the UserService that emits on an Observable allowing the different UI components to be refreshed.

What I would like is to be able, somehow, to subscribe to this Observable in the guard and then re-evaluate it when the logout event fires in order to see if the current route can still be activated. The aim behind this is to be able to redirect the user to the homepage if he logs out while still on an admin page.

Upvotes: 2

Views: 1035

Answers (1)

Robin Dijkhof
Robin Dijkhof

Reputation: 19288

Options:

1: Create a directive which you could add at the highest level(probable to your app.component). Within this directive, subscribe to your observable. Within you subscribe method, use the activateRoute.snapshot to check your current path. Redirect if necessary.

2: Create a directive which you could add at the highest level(probable to your app.component). Within this directive, subscribe to your observable and refresh the page in your subscribe.

3: A guard is basically nothing else than a service. You could simply subscribe to the canActivate method.

Upvotes: 1

Related Questions