【问题标题】:Angular route parameter value is replaced with name of parameter in AuthGuard canLoad角度路由参数值替换为 AuthGuard canLoad 中的参数名称
【发布时间】: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


【解决方案1】:

我尝试使用 canLoad 的第二个参数,类型为 UrlSegment[],如下面的代码所示。它似乎正在工作。我希望这适用于所有情况下的所有路线。如果有人知道这可能导致的任何问题,请告诉我。

    canLoad(route: Route, segments: UrlSegment[]) {
        if (this.validateTokenAccess()) {
           return true;
        }

        // const url = `/${route.path}`;
        const url = segments.map(s => s.path).join('/');
    
        this.authService.redirectTo = url;
        this.authService.handleAuthentication();
        return false;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-15
    • 2015-11-03
    • 2018-05-17
    • 1970-01-01
    • 2019-10-15
    • 1970-01-01
    • 2018-03-20
    相关资源
    最近更新 更多