From the Angular documentation on canActivate,似乎你只能使用canActivate防护来允许在canActivate函数最终返回true时继续进行路由.
有没有办法说,“只有在canActivate类评估为false时才进入这条路线”?
例如,为了不允许登录用户访问登录页面,我尝试了这个但是它不起作用:
- export const routes: Route[] = [
- { path: 'log-in',component: LoginComponent,canActivate: [ !UserLoggedInGuard ] },
我在控制台中遇到此错误:
- ERROR Error: Uncaught (in promise): Error: StaticInjectorError[false]:
- StaticInjectorError[false]:
- NullInjectorError: No provider for false!
- Error: StaticInjectorError[false]:
- StaticInjectorError[false]:
- NullInjectorError: No provider for false!
你问题中有趣的是配方:
Is there some way to say,“only proceed to this route if the
canActivate class evaluates to false” ?
以及您如何表达“直观”的解决方案:
- { path: 'log-in',
基本上说,你需要否定UserLoggedInGuard @ canActivate的结果
让我们考虑UserLoggedInGuard的以下实现:
- @Injectable()
- export class UserLoggedInGuard implements CanActivate {
- constructor(private _authService: AuthService) {}
- canActivate(route: ActivatedRouteSnapshot,state: RouterStateSnapshot): boolean {
- return this._authService.isLoggedIn();
- }
- }
接下来,让我们看看@Mike提出的解决方案
- @Injectable()
- export class NegateUserLoggedInGuard implements CanActivate {
- constructor(private _authService: AuthService) {}
- canActivate(route: ActivatedRouteSnapshot,state: RouterStateSnapshot): boolean {
- return !this._authService.isLoggedIn();
- }
- }
现在,方法还可以,但与UserLoggedInGuard的(内部)实现紧密相关.如果由于某种原因UserLoggedInGuard @ canActivate的实现发生了变化,NegateUserLoggedInGuard将会中断.
我们怎么能避免这种情况?简单的滥用依赖注入:
- @Injectable()
- export class NegateUserLoggedInGuard implements CanActivate {
- constructor(private _userLoggedInGuard: UserLoggedInGuard) {}
- canActivate(route: ActivatedRouteSnapshot,state: RouterStateSnapshot): boolean {
- return !this._userLoggedInGuard.canActivate(route,state);
- }
- }
现在这正是你所表达的
- canActivate: [ !UserLoggedInGuard ]
最好的部分:
>它与UserLoggedInGuard的内部实现紧密耦合>可以扩展以操纵多个Guard类的结果