【发布时间】:2021-01-07 17:32:32
【问题描述】:
在我的 AuthGuardService 中,我有 canLoad 函数,它采用 Route 类型的参数。 然后,我将身份验证重定向 url 分配给该 Route 参数的路径属性。
但是,发生了一些奇怪的事情, - 如果路径包含路由参数,那么在路径属性中,该参数被替换为参数的名称。例如 /hello/world/123 变成 /hello/world/:id。
这意味着如果更新身份验证(例如重新加载页面时),用户将被重定向到 /hello/world/:id。
我该如何解决这个问题?
我正在使用 Angular 8。
这是来自 app-routes.ts:
{
path: 'hello/world/:id',
loadChildren: () => import('./world/world.module').then(m => m.WorldModule),
canActivate: [AuthGuardService],
canActivateChild: [AuthGuardService],
canLoad: [AuthGuardService],
}
世界路由.module.ts
const routes: Routes = [
{
path: '',
component: WorldComponent
},
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class WorldRoutingModule {}
world.module.ts
@NgModule({
declarations: [
WorldComponent
],
imports: [
WorldRoutingModule,
CommonModule,
TranslateModule.forChild(),
FormsModule
],
exports: [
WorldComponent
],
providers: [L10nService],
entryComponents: [],
})
export class WorldModule {}
来自 AuthGuardService
canLoad(route: Route) {
if (this.validateTokenAccess()) {
return true;
}
const url = `/${route.path}`;
this.authService.redirectTo = url;
this.authService.handleAuthentication();
return false;
}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (this.validateTokenAccess()) {
return true;
}
this.authService.redirectTo = state.url;
this.authService.handleAuthentication();
return false;
}
canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.canActivate(route, state);
}
【问题讨论】:
-
您还可以访问 canLoad(第二个参数)中的段,所以可能需要调查一下?
-
感谢@MikeOne!我尝试使用segments 参数,我认为它正在工作。有关代码详细信息,请参阅我的答案。
-
不错!很高兴它有帮助。
标签: angular auth-guard