订阅未在角度2中定义?

时间:2017-02-02 06:34:24

标签: angular typescript

我正在Angular 2中创建一个演示应用程序,并希望在我的组件中控制params['id'],id来自查询参数。

为了达到这个目的,我在我的组件中这样做:

ngOnInit(): void {
     this.route.params
          .switchMap(
           (params: Params) => 
                this.heroService.getHero(+params['id']);
                console.log("ID :",params['id'])
           ).subscribe(hero => this.hero = hero);
    };

但我收到了这个错误:

core.umd.js:3491 EXCEPTION: Uncaught (in promise): Error: Error in :0:0 caused by: params is not defined
ReferenceError: params is not defined

请建议我必须做些什么来安慰param的id?

2 个答案:

答案 0 :(得分:3)

您需要{}向箭头函数添加更多语句。我想你可能想做:

    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函数中订阅。在箭头功能的情况下 ()=>statment相当于()=>{return statement;}

当您添加其他语句并使用大括号时,您需要添加缺少的返回。

答案 1 :(得分:1)

如果您需要多个语句,则需要一个块{}

ngOnInit(): void {
  this.route.params
  .switchMap((params: Params) => {
    var hero = this.heroService.getHero(+params['id']);
    console.log("ID :",params['id']);
    return hero;
  })
  .subscribe(hero => this.hero = hero);
}

ngOnInit(): void {
  this.route.params
  .switchMap((params: Params) => {
    console.log("ID :",params['id']);
    return this.heroService.getHero(+params['id']);
  })
  .subscribe(hero => this.hero = hero);
}
相关问题