【问题标题】:Access to parent router params in Angular 14访问 Angular 14 中的父路由器参数
【发布时间】:2022-12-13 00:35:53
【问题描述】:

使用 Angular 14,有一个路由配置:

const routes: Routes = [{
    path: ':page',
    component: PageComponent,
    children: [
      {
        canActivate: [ValidPathGuard],
        path: ':subPage',
        component: SubPageComponent
      }
    ]
  }
]

有效路径保护:

export class ValidPathGuard implements CanActivate {
  canActivate(route: ActivatedRouteSnapshot) {
    console.log(route);
  }
}

route.params 仅输出:{subPath: 'subPath'}

如果我想访问 :page 需要使用 route.parent.params: {path: 'path'}

但是,如果我将使用三级路线怎么办。

问题是我怎样才能得到所有参数的对象? 喜欢: { 路径:'路径', 子路径:'子路径' }

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    尝试访问路由的父实例并继续搜索父实例,直到没有父实例(使用递归)

    function mergeRouteParams(route: ActivatedRouteSnapshot, getter: (r: ActivatedRouteSnapshot) => Params): Params {
        if (!route) {
            return {};
        }
        const currentParams = route.params;
        return { ...mergeRouteParams(route.parent), ...currentParams };
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-12
      • 1970-01-01
      • 1970-01-01
      • 2021-05-14
      • 2016-02-16
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      相关资源
      最近更新 更多