在我的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
);
关于如何实现这一目标的想法?
答案 0 :(得分:1)
这就是我能够做到的:
只需像这样导航:
<span class="cursor-pointer" [routerLink]="['/']" [queryParams]="{ 'id': 82860}">Edit</span>
在Root Component
中得到它:
this.route.snapshot.queryParamMap.get('id')
我们不需要为查询参数定义路由。它会显示在您的网址中:http://localhost:4200/?id=82860
。
答案 1 :(得分:0)
文档非常清楚地说明如何在路线中共享参数:
HTML模板:
<a [routerLink]="['/hero', hero.id]">
<span class="badge">{{ hero.id }}</span>{{ hero.name }}
</a>
或在组件中:
gotoHeroes(hero: Hero) {
let heroId = hero ? hero.id : null;
// Pass along the hero id if available
// so that the HeroList component can select that hero.
// Include a junk 'foo' property for fun.
this.router.navigate(['/heroes', { id: heroId, foo: 'foo' }]);
}
组件:
export class HeroListComponent implements OnInit {
heroes$: Observable<Hero[]>;
private selectedId: number;
constructor(
private service: HeroService,
private route: ActivatedRoute
) {}
ngOnInit() {
this.heroes$ = this.route.paramMap.pipe(
switchMap((params: ParamMap) => {
// (+) before `params.get()` turns the string into a number
this.selectedId = +params.get('id');
return this.service.getHeroes();
})
);
}
}
答案 2 :(得分:-1)
所以你不需要定义没有参数的路线:
const routes: Routes = [
{path: '/:id', component: DashboardComponent, pathMatch: 'full', canActivate: [AuthGuard]},
{path: 'users', component: UsersComponent, canActivate: [AuthGuard]},
];
在你的组件中,只检查id是否为null:
this.route.params.subscribe( params => {
if(params['id'] == null) {
// do what u need
}
}