微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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;
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?