【问题标题】:subscribe is not defined in angular 2?订阅未在 Angular 2 中定义?
【发布时间】:2017-06-19 03:16:48
【问题描述】:

我正在 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

请建议我必须做什么来控制参数的 id ?

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

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

        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;}

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

    【讨论】:

    • 谢谢,让我试试这个。
    • 但是为什么要返回 this.heroService.getHero(+params['id']) 呢? @Suraj
    【解决方案2】:

    如果你想要多个语句,你需要一个块{}

    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);
    }
    

    【讨论】:

    • 谢谢@Günter Zöchbauer,让我检查一下。
    • 我认为你错过了 switchmap 回调中的返回
    • 这不起作用,我得到了这个异常:- core.umd.js:3491 异常:未捕获(承诺):错误:错误:0:0 导致:您提供了“未定义”预期有流的地方。您可以提供 Observable、Promise、Array 或 Iterable。 TypeError:您在预期流的位置提供了“未定义”。您可以提供 Observable、Promise、Array 或 Iterable。
    • 我很难知道你试图完成什么。 this.heroService.getHero() 返回什么?我还添加了来自 suraj 的建议。如果你想实际返回一些东西,一个块需要一个显式的return,而switchMap 需要一个返回值。
    • 老实说,我不知道你的问题是什么或你试图完成什么。 subscribe() 返回一个Subscription,您可以将其用于unsubscribe()
    猜你喜欢
    • 1970-01-01
    • 2017-12-26
    • 2021-04-27
    • 1970-01-01
    • 2016-10-28
    • 1970-01-01
    • 2016-10-09
    • 2021-05-16
    • 1970-01-01
    相关资源
    最近更新 更多