我有一个angular2主动防护装置处理,如果用户没有登录,把它重定向到登录页面:如何在所有路线上应用canActivate警戒?
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选项而不必将其添加到每个路径。
我想要的是将其添加到主路线上,并且它应该适用于所有其他路线。我已经搜索了很多,但我无法找到任何有用的解决方案
感谢
谢谢,它现在的作品 –
很高兴听到:)感谢您的反馈。 –
@GünterZöchbauer我总是阅读你的建议。非常感谢你!!但在我的情况下,这是行不通的。 CanActive不适用于儿童之间的路由。我使用canActivateChild。有用。 – Smiranin