订阅未在角度2中定义? [英] subscribe is not defined in angular 2?
问题描述
我正在Angular 2中创建一个演示应用程序,并希望在我的组件中控制台 params ['id']
,id来自查询参数.
I am creating a demo app in Angular 2 and want to console params['id']
in my component, id is coming from query params.
要实现这一点,我需要在组件中执行以下操作:
To achieve this I am doing this in my component:
ngOnInit(): void {
this.route.params
.switchMap(
(params: Params) =>
this.heroService.getHero(+params['id']);
console.log("ID :",params['id'])
).subscribe(hero => this.hero = hero);
};
但是我得到了这个错误:
But i got this error:
core.umd.js:3491 EXCEPTION: Uncaught (in promise): Error: Error in :0:0 caused by: params is not defined
ReferenceError: params is not defined
请提出我需要做些什么来控制参数的ID?
Please suggest what I will have to do to console the param's id ?
推荐答案
您需要具有 {}
才能向箭头函数添加更多语句.我想您可能想做:
You need to have {}
to add more statements to an arrow function. I think you might want to do:
ngOnInit(): void {
this.route.params
.switchMap((params: Params) => {
console.log("ID :",params['id']));
return this.heroService.getHero(+params['id']);
}) .subscribe(hero => this.hero = hero);
};
为什么要回来?
switchmap返回的Observable在 subscribe
函数中进行了订阅.如果是箭头功能()=>声明
等同于()=> {return statement;}
The Observable that is returned by switchmap is subscribed in subscribe
function. In case of arrow functions
()=>statment
is equivalent to ()=>{return statement;}
当您添加其他语句并使用花括号时,您需要添加缺失的收益.
When you add an additional statement and use brace you need to add the missing return.
这篇关于订阅未在角度2中定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!