首页 > 解决方案 > 在儿童中访问路线参数

问题描述

我正在尝试从孩子那里访问参数,但似乎无法访问它们。我的路线组织如下:

const clientsRoutes: Routes = [
  {
    path: 'clients',
    component: ClientIndexPage,
    // loadChildren: "./client-index/client-index.module#ClientIndexPageModule",
    canActivate: [AuthGuard],
  },
  { path: 'clients/:id',
    component: ClientDetailPage,
    canActivate: [AuthGuard],
    canActivateChild: [AuthGuard],
    children: [
      {
        path: 'profile',
        component: ProfilePage
        // loadChildren: './client-detail/profile/profile.module#ProfilePageModule',
      },
      {
        path: 'finance',
        component: FinancePage
        // loadChildren: './client-detail/finance/finance.module#FinancePageModule'
      },
      {
        path: '',
        redirectTo: 'profile',
        pathMatch: 'full'
      }
    ]
  },
];

ClientDetailPage我可以访问:id,但是当我尝试从 中获取它时ProfilePage,它无法访问:

// ClientDetailsPage
console.log(this.route.snapshot.paramMap.get('id)
// returns the correct value

// ProfilePage
console.log(this.route.snapshot.paramMap.get('id))
// returns null
console.log(this.route.parent)
//returns null

有什么我想念的吗?可能值得注意的是ClientDetailsPageProfilePage两者都有单独的模块。

标签: angularrouting

解决方案


以下将访问已激活路由的 id 参数。

this.route.snapshot.paramMap.get('id');

但是使这不起作用的是被认为是激活的路线。只有匹配的确切子路由被认为是激活的路由,因此包含 id 参数的路由的父级不在激活的路由中。

// assuming a route like clients/2/profile
{
    path: 'profile',
    component: ProfilePage
}

好消息是您可以访问该路由的父对象,如下所示。

// calling route.parent moves us one route up the tree, where id is a param
this.route.parent.snapshot.paramMap.get('id');

推荐阅读