在我的 Angular 10 应用程序中,我有一个带有多个子路由的路由,上面有一个 canActivate 保护。
{
path: 'settings', component: SettingsComponent,
children: [
{ path: '', redirectTo: 'index-types', pathMatch: 'full' },
{
path: 'index-types', component: IndexTypesComponent,
resolve: [IndexTypeResolverService],
canActivateChild: [ErrorPageGuard],
children: [
{ path: '', component: IndexTypeStartComponent },
{ path: 'new', component: IndexTypeEditComponent },
{
path: ':id',
component: IndexTypeDetailComponent,
resolve: [IndexTypeResolverService]
},
{
path: ':id/edit',
component: IndexTypeEditComponent,
resolve: [IndexTypeResolverService]
}
]
},
{ path: 'users', component: UsersComponent }
]
}
我正在尝试获取 canActivtate 保护,以防止用户输入带有 :id 和 :id/edit 路由中不存在的 ID 的 URL。canActivate 似乎在防止用户在 URL 中输入不存在的 id 方面做得很好,但问题是当用户手动输入正确的 id 时,它的行为就像它不正确一样 - 但是当单击具有相同正确ID的routerLink它可以工作。
我试图调试它,并得出结论,在下面的代码中,this.indexTypeService
应该有一个我的 indexTypes 列表实际上在该列表中没有任何内容,只有在用户手动输入任何内容的情况下地址栏:
export class ErrorPageGuard implements CanActivate, CanActivateChild {
constructor(private indexTypeService: IndexTypeService, private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
//TODO: works when navigating programmatically, but not when navigating manually
let state_id = state.url.split('/')[state.url.split('/').length - 1];
let route_id = +route.params.id;
let id = Object.keys(route.params).length > 0 ? route_id : (!isNaN(+state_id) ? +state_id : -1);
if ((Object.keys(route.params).length === 0)
|| (this.indexTypeService.getIndexType(id) !== undefined)) {
return true;
}
else {
this.router.navigate(['/']);
return false;
}
}
canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.canActivate(route, state);
}
}
我究竟做错了什么?