如何从Angular ActivatedRoute获取参数 [英] How to get parameters from the Angular ActivatedRoute
本文介绍了如何从Angular ActivatedRoute获取参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用可观察性从激活的路线中获取prameter:id.当我在控制台上打印参数时,我会得到正确的:id值.但是this.id并非如此.我得到的值是NaN.你能告诉我是什么问题吗
I'm trying to get the prameter :id from my activated route using observables. When I print params on the console I get the right values for :id. But it's not the case for this.id. I get the value NaN. Can you tell me what is the problem
export class RecipeEditComponent implements OnInit {
id: number;
editMode = false;
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route.params.subscribe(
(params: {id: string}) => {
this.id = +params.id;
console.log(this.id);
}
);
}
}
推荐答案
更改为 this.id = + params.get('id')
.
您应该使用方法 get()
,因为它为给定的参数 id
返回单个值.您收到错误消息是因为 params
不是以 id
为值的键.
You should use the method get()
because it returns a single value for the given parameter id
.
You were getting an error because params
is not a key with id
as a value.
export class RecipeEditComponent implements OnInit {
id: number;
editMode = false;
constructor(private route: ActivatedRoute) { }
ngOnInit() {
// paramMap replaces params in Angular v4+
this.route.paramMap.subscribe(params: ParamMap => {
this.id = +params.get('id');
console.log(this.id);
});
}
这篇关于如何从Angular ActivatedRoute获取参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文