我试图像护角文件一样放置一个儿童看守:
@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;
}
}
Run Code Online (Sandbox Code Playgroud)
我的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,
}]
}
]
Run Code Online (Sandbox Code Playgroud)
我将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
Run Code Online (Sandbox Code Playgroud)
通常,如果我没有经过身份验证,则需要将我重定向到登录页面。有人得到这个错误还是知道为什么要午餐?
谢谢
该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,
}]
}
]
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
如果找到我的解决方案。我为其他有同样问题的人解释。
就像例外一样,路由模块是子路由模块这一事实会引发此错误。我需要在 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 {}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8141 次 |
| 最近记录: |