我试图像角度doc一样建立一个儿童看守:
@Injectable() export class AuthGuardService implements CanActivate,CanActivateChild { constructor(private authService: AuthentificationService,private router: Router) {} canActivate(route: ActivatedRouteSnapshot,state: RouterStateSnapshot): boolean { let url: string = state.url; return this.checkLogin(url); } canActivateChild(route: ActivatedRouteSnapshot,state: RouterStateSnapshot): boolean { return this.canActivate(route,state); } checkLogin(url: string): boolean { /*****/ return false; } }
我的routing.module:
import { AuthGuardService } from '../services/auth-guard.service'; const routes = [ { path: '',component: MyComponent,canActivate: [AuthGuardService],children: [{ path: '',canActivateChild: [AuthGuardService],children: [ { path: 'candidature',component: ListCandidatureComponent,},{ path: 'candidature/new',component: NewCandidatureComponent }] },{ path: 'login',component: LoginComponent,}] } ]
我将canActivateChild保护放在无组件部分上,以通过身份验证来保护此路由.
但是使用这种配置,当我试图达到’my.site.com/candidature’时,我遇到了这个错误:
Unhandled Promise rejection: guard is not a function ; Zone: angular ; Task: Promise.then ; Value: TypeError: guard is not a function
通常,如果我没有被认证,我需要被重定向到登录页面.
有人得到这个错误或者知道它为什么会被淘汰?
谢谢
解决方法
canActivateChild:[AuthGuardService]不应该在子节点内,而是在父节点上声明.
不确定,当你在孩子里面宣布孩子时,你需要在外面的孩子中宣布canActivateChild.但你可以测试有没有它.如果有效,请告诉我!
const routes = [ { path: '',canActivateChild: [AuthGuardService] // it should be placed here! children: [{ path: '',// canActivateChild: [AuthGuardService],// needed or not? children: [ { path: 'candidature',}] } ]
希望这可以帮助!