我有一个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选项而不将其添加到每个路径。
我要在主路线上添加它,并且它应适用于所有其他路线。我已经搜索了很多,但是找不到任何有用的解决方案
谢谢