【问题标题】:Accessing route params in children在儿童中访问路线参数
【发布时间】:2019-04-26 22:35:46
【问题描述】:

我正在尝试访问孩子的参数,但似乎无法访问它们。我的路线安排如下:

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 都有单独的模块。

【问题讨论】:

标签: angular routing


【解决方案1】:

以下将访问已激活路由的 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');

【讨论】:

    猜你喜欢
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-13
    • 1970-01-01
    相关资源
    最近更新 更多