How to apply canActivate guard on all the routes?

前端 未结 3 1392
慢半拍i
慢半拍i 2020-12-12 20:29

I have a angular2 active guard which handle if the user is not logged in, redirect it to login page:

import { Injectable } from  \"@angular/core\";
import {          


        
相关标签:
3条回答
  • 2020-12-12 20:51

    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 }
        ]}
    ];
    
    0 讨论(0)
  • 2020-12-12 21:02

    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.

    0 讨论(0)
  • 2020-12-12 21:02

    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

    0 讨论(0)
提交回复
热议问题