我试着安排一个像angular 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
通常,如果我没有通过身份验证,我需要被重定向到登录页面。有没有人知道这个错误,或者知道为什么要用午餐?
感谢‘s
发布于 2017-02-28 08:56:04
如果找到我的解决方案。我为其他有同样问题的人解释。
与excepted一样,routing-module是子路由模块这一事实会引发此错误。我需要在de AppRouting中提供要用于子舍入模块的AuthGuardService,如下所示:
@NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [RouterModule],
declarations: [],
providers: [AuthGuardService] //Here add the AuthGuardService to be available in route-module-child
})
export class AppRoutingModule {}
发布于 2017-02-27 09:40:14
canActivateChild: [AuthGuardService],
不应位于children
内部,而应在父路由中声明。
不是很确定,当你声明了子级中的子级时,你也需要在外部的子级中声明canActivateChild
。但是您可以使用它或不使用它进行测试。如果有效,请让我知道!
const routes = [
{
path: '',
component: MyComponent,
canActivate: [AuthGuardService],
canActivateChild: [AuthGuardService] // it should be placed here!
children: [{
path: '',
// canActivateChild: [AuthGuardService], // needed or not?
children: [
{
path: 'candidature',
component: ListCandidatureComponent,
},
{
path: 'candidature/new',
component: NewCandidatureComponent
}]
}, {
path: 'login',
component: LoginComponent,
}]
}
]
希望这能有所帮助!
https://stackoverflow.com/questions/42473026
复制相似问题