我需要将id作为参数传递给我的角度分量
在我的html中,我有这样的
<a [routerLink]="['/viewjobdetail', currentJob.id]">
{{ currentJob.title }}
</a>
app.module.tsRouterModule.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']);
});
但当我检查它时,它总是显示a的未定义,我在这里做错了什么?}
您应该使用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;
}