Angular 路由参数值替换为 AuthGuard canLoad 中的参数名称

问题描述

在我的 AuthGuardService 中,我有 canLoad 函数,该函数采用 Route 类型的参数。 然后我将我的身份验证重定向 url 分配给该 Route 参数的 path 属性

然而,发生了一些奇怪的事情, - 如果路径包含路由参数,则在路径属性中,该参数将替换为参数的名称。例如 /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],}

world-routing.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 的第二个参数,类型为 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;
    }

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...