有没有办法配置Angular路由器中使用的canActivate
防护?
拥有此SessionGuard
:
@Injectable()
export class SessionGuard implements CanActivate {
public requireLeagues: boolean = true;
constructor(private authService: AuthService, private session: SessionService, private router: Router) {
}
async canActivate(): Promise<boolean> {
if (!this.authService.isLoggedIn) {
return false;
}
await this.session.start();
if (this.requireLeagues && (!this.session.leagues || this.session.leagues.length == 0)) {
//Redirect to create league page
this.router.navigate(['/create-league']);
return false;
} else {
return true;
}
}
}
这条路线:
const routes: Routes = [
{path: '', component: HomeComponent, canActivate: [AuthGuard, SessionGuard]},// <-- requireLeagues = false
{path: 'login', component: LoginComponent},
{path: 'leagues', component: [AuthGuard, SessionGuard]},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
我想将requireLeagues
设置为true或false,具体取决于路线,而无需创建新的,不同的后卫。这可能吗?
答案 0 :(得分:1)
是的,canActivate
方法已通过当前ActivatedRouteSnapshot
和RouterStateSnapshot
。
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
this.requireLeages = route.params... // something from route
}
这是ActivatedRouteSnapshot的docs。它有很多有用的属性,包括data
属性,可用于存储自己的数据以在路由和服务之间共享。