【问题标题】:Angular - Dynamic routing with router param vaiableAngular - 带有路由器参数变量的动态路由
【发布时间】:2021-12-01 00:08:42
【问题描述】:

我想在我的 routing.module.ts 中做这样的事情(见用--> 标记的行)

export const routes: Routes = [
        path: 'test/:action',
        component: CreateComponent,
        --> canActivate: ':action' == 'read' ? [Guard1] : [Guard1, Guard2],
        data: {
        -->  screenAction: ':action' == 'read' ? 'read' : ':action',
        }
]

我必须使用变量 :action 因为它稍后会在路由器参数中使用。感谢您的帮助!

【问题讨论】:

    标签: javascript angular typescript routes angular-router-guards


    【解决方案1】:

    嗯,你问的是可能的,但实现它可能有点复杂。

    首先,你需要定义多个路由而不是1个。你可以在哪里应用你需要的条件。

    const routes: Routes = [
      { path: '', redirectTo: '/home', pathMatch: 'full' },
      { path: 'home', component: AppComponent },
      {
        path: 'dummy1/:action',
        component: Dummy1Component,
        canActivate: [GuardRotaterGuard],
      },
      {
        path: 'dummyx/:action',
        component: Dummy2Component,
        canActivate: [Guard1Guard],
      },
      {
        path: 'dummyz/:action',
        canActivate: [Guard1Guard, Guard2Guard],
        component: Dummy2Component,
      },
    ];
    

    路由dummy1/:action 就像一个网关路由。每个对 dummy2 组件的请求都应该从这里开始。然后你需要一个可以根据路由参数决定和轮换路由的决策者/旋转器守卫。 它应该如下所示:

    canActivate(
        next: ActivatedRouteSnapshot,
        statex: RouterStateSnapshot
      ): Observable<boolean> | Promise<boolean> | boolean {
        const { action } = next.params;
        const state = { comesFrom: 'rotater' };
        console.log("rotater",action);
        if (action === 'read') { // you can decide whatever you want here
           this.router.navigate(['/dummyx/read'], { state });
        }else{
          this.router.navigate(['/dummyz', action], { state }); // pass the action to the other route as a parameter
        }
    
         return true;
      }
    

    here 是 Stackblitz 的一个实际例子。

    【讨论】:

    • @elder 感谢您的回复。关于 screenAction 是否与您在 router.navigation() 方法中传递的状态相对应?
    • @BenSaad dummy1 路由永远不会被路由,这就是您看不到 dummy1 组件的原因。在没有组件的路线上使用守卫是一个长期存在的问题,所以我更喜欢这种方式。
    • 路由器配置数据中的@BenSaad 用于您不能动态使用的静态数据。因此,如果要传递动态数据状态或路由参数是可行的方法。如果您提供一些关于您将在何处以及如何使用screenAction 的信息,我们可以决定您需要使用什么。
    • 再次感谢@Eldar!但有一个问题。如果它读取了您对 dummyx/:action 的重定向,否则您将重定向到 dummyz/:action。因此,如果是读取或其他操作,则 url 中的路径是不同的。我希望所有动作的路径开始都相同。 (例如 dummyX/read 和 dummyX/write)。
    • @BenSaad 在角度路由配置中是静态的。因此默认情况下您不能在运行时更改规则。如果你想要这种行为,你需要在这里编写一个看起来像旋转器保护的保护,它应该根据条件手动执行 guard1 和 guard2 的检查。还有一种可能性是使用名为aop-routing 的库。它提供了动态操纵路线的能力。 Article
    猜你喜欢
    • 1970-01-01
    • 2018-04-25
    • 2018-04-28
    • 1970-01-01
    • 2020-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    相关资源
    最近更新 更多