问题描述
我需要将 id 作为参数传递给我的角度组件
在我的 html 中,我有这样的东西
<a [routerLink]="['/viewjobdetail',currentJob.id]">
{{ currentJob.title }}
</a>
app.module.ts RouterModule.forRoot 配置为
{ path: 'viewjobdetail/:id',component: JobDetailComponent }
在我的调用组件中
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute){}
ngOnInit(): void {
this.route.queryParams.subscribe(params => {
debugger;
var a = params['id'];
this.displayJobId = parseInt(params['id']);
});
但是当我检查它时,它总是显示 undefined ,我在这里做错了什么? }
解决方法
您应该使用params
或paramMap
而不是queryParams
,查询参数只能识别像viewjobdetail?id=23
这样传递的查询参数
queryParams
更好,因为 params
在未来版本中可能会被弃用
this.route.paramMap.subscribe(paramMap => {
debugger;
var a = paramMap.get('id');
this.displayJobId = parseInt(a);
});
,
我得到了解决方案。为了实现这一点,我们需要使用带有 queryParams 的查询参数。我修改了我的html如下
<a [routerLink]="['/viewjobdetail']" [queryParams]="{id: currentJob.id}">
{{ currentJob.title }}
</a>
在 app.module.ts 中
{ path: 'viewjobdetail',component: JobDetailComponent }
然后在我的调用组件中
this.route.queryParams.subscribe(params => {
var a = params.id;
}