We all agreed about not manipulating data inside component or better to say presentation layer.
So I decided to put logout logic inside guard, this way I will be able to just call logout
route and done!
For this I've configured my authentication module routes like this:
{
path: 'login',
component: AuthComponent,
data: { registering: false }
},
{
path: 'register',
component: AuthComponent,
data: { registering: true }
},
{
path: 'logout',
component: AuthComponent,
data: { registering: false },
canActivate: [LogoutGuard]
}
I love to keep things as simple and low as possible
😁
For log out I've added canActivate
field and passed the LogoutGuard
, the guards have the ability to return UrlTree
. It is awesome, let's see how the guard implemented:
@Injectable()
export class LogoutGuard implements CanActivate {
constructor(private store: Store, private router: Router) {
}
canActivate(): UrlTree {
this.store.dispatch(logout());
return this.router.createUrlTree(['auth', 'login']);
}
}
That's it!
The canActivate
method is dispatching logout
action from NgRx
solution and then returning the URL tree which is created using Router
from angular/router
library!
After this, all we need, any where in the APP we can just redirect user to auth/logout
and expect it work as expected and user will automatically will be redirected to auth/login
route.
Thank you for reading 🙏🏽
Hope you liked ☕
Top comments (0)