首页 > 解决方案 > Angular 6将查询参数传递给根

问题描述

在我app.routing.module.ts的配置中,我配置了以下路线:

{
  path: '',
  redirectTo: 'dashboard',
  pathMatch: 'full',
}, {
  path: '',
  component: AdminLayoutComponent,
  children: [{
    path: '',
    loadChildren: './admin/admin.module#AdminModule'
  }]
}

我想将一个可选的查询参数传递给应用程序的根,在我的例子中是DashboardComponent.

在我的AdminModule我配置我的路线是这样的:

const routes: Routes = [
  {path: '', component: DashboardComponent, pathMatch: 'full', canActivate: [AuthGuard]},
  {path: '/:id', component: DashboardComponent, pathMatch: 'full', canActivate: [AuthGuard]},
  {path: 'users', component: UsersComponent, canActivate: [AuthGuard]},
];

如果我在仪表板组件中执行此操作,我似乎无法访问该 id 参数:

this.route.params.subscribe(
  params => console.log(params) // I get nothing here
);

关于如何实现这一目标的想法?

标签: angularangular5angular6

解决方案


这就是我能够做到的方式:

只需像这样导航:

<span class="cursor-pointer" [routerLink]="['/']" [queryParams]="{ 'id': 82860}">Edit</span>

Root Component像这样得到它:

this.route.snapshot.queryParamMap.get('id')

我们不需要为查询参数定义路由。它会像这样出现在您的网址中:http://localhost:4200/?id=82860.


推荐阅读