【问题标题】:How to use observables in angular2 service calls?如何在 angular2 服务调用中使用 observables?
【发布时间】:2016-05-31 14:54:23
【问题描述】:

我有一个来自我的组件的服务调用,它获取英雄列表。从该函数调用另一个具有 http 请求的函数...我如何订阅函数调用,以便我能正确获得响应...这是我的 plunker 演示 http://plnkr.co/edit/UM9STMwaOsgolhBjADjx?p=preview ... 这就是我从组件调用服务的方式

 ngOnInit() { 
              this.heroService.getHeroes()
                 .subscribe(
                  heroes => this.heroes = heroes,
                  error =>  this.errorMessage = <any>error);
 }

在我的服务类中,我调用了这个方法,该方法调用了另一个具有 http 请求并订阅了该方法的方法...

  getHeroes (){
return this.GetListOfHeroes()
        .subscribe((data: any) => {
            return data;
        }
        );
}

最后这是获取列表的方法...

  GetListOfHeroes(){
    return this.http.get(this.heroesUrl)
                .map(this.extractData)
                .catch(this.handleError);
 }

如果我直接从我的组件调用 GetListOfHeroes() 方法,它工作正常,但如果我尝试从另一个方法调用它,它会显示此错误 this.heroService.getHeroes(...).subscribe is not a function 有人请告诉我我在哪里做错了......谢谢

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

    getHeroes() 中使用.map(...) 而不是.subscribe(...),例如:

      getHeroes (){
        return this.GetListOfHeroes()
        .map((data: any) => {
            return data;
        });
      }
    

    这样getHeroes()会返回Observable,而.subscribe()会返回Subscription,您无法订阅。

    【讨论】:

      【解决方案2】:

      事实上,您应该在getHeroes 方法中订阅,因为它会返回订阅而不是可观察的。

      getHeroes (){
        return this.GetListOfHeroes()
          .subscribe((data: any) => { // <-----
              return data;
          });
      }
      

      subscribe 方法只能在 observable 上调用。订阅对象可用于取消订阅...

      事实上,这取决于你想在getHeroes 方法中做什么。例如,您可以利用do 运算符或map 之一。这是一个示例:

      getHeroes (){
        return this.GetListOfHeroes()
          .do((data: any) => { // <-----
            // do something with data
          })
          .map((data: any) => {
            // return something else in the data flow
            return { attr: 'value' };
          });
      }
      

      【讨论】:

        猜你喜欢
        • 2017-01-27
        • 2017-06-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-30
        • 2016-08-18
        相关资源
        最近更新 更多