如何应用可以激活所有路线的警卫?

我有一个 angular2活动警卫,处理如果用户没有登录,重定向到登录页面:

import { Injectable } from  "@angular/core";
import { CanActivate , ActivatedRouteSnapshot, RouterStateSnapshot, Router} from "@angular/router";
import {Observable} from "rxjs";
import {TokenService} from "./token.service";


@Injectable()
export class AuthenticationGuard implements CanActivate {


constructor (
private router : Router,
private token : TokenService
) { }


/**
* Check if the user is logged in before calling http
*
* @param route
* @param state
* @returns {boolean}
*/
canActivate (
route : ActivatedRouteSnapshot,
state : RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
if(this.token.isLoggedIn()){
return true;
}
this.router.navigate(['/login'],{ queryParams: { returnUrl: state.url }});
return;
}
}

我必须在每条路线上实现它,比如:

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

有没有更好的方法来实现 canActive 选项,而不需要将它添加到每个路径中。

我想要的是把它添加到主路线,它应该适用于所有其他路线。我找了很多,但是没有找到任何有用的解决办法

谢谢

43558 次浏览

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 }
]}
];

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

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.