How to apply canActivate guard on all the routes? How to apply canActivate guard on all the routes? angular angular

How to apply canActivate guard on all the routes?


You can introduce a componentless parent route and apply the guard there:

const routes: Routes = [    {path: '', canActivate:[AuthenticationGuard], children: [      { path : '', component: UsersListComponent },      { path : 'add', component : AddComponent},      { path : ':id', component: UserShowComponent },      { path : 'delete/:id', component : DeleteComponent },      { path : 'ban/:id', component : BanComponent },      { path : 'edit/:id', component : EditComponent }    ]}];


You can also subscribe to the router's route changes in your app.component's ngOnInit function and check authentication from there e.g.

    this.router.events.subscribe(event => {        if (event instanceof NavigationStart && !this.token.isLoggedIn()) {            this.router.navigate(['/login'],{ queryParams: { returnUrl: state.url}});         }    });

I prefer this way of doing any kind of app wide check(s) when a route changes.


I think you should implement "child routing" which allow you to have a parent (with a path "admin" for example) and his childs.

Then you can apply a canactivate to the parent which will automatically restrict the access to all his child. For example if I want to access "admin/home" I'll need to go throught "admin" which is protectected by canActivate. You can even define a parent with an empty path "" if you want