订阅observable返回undefined [英] Subscribe to observable is returning undefined

查看:541
本文介绍了订阅observable返回undefined的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图订阅一个从本地JSON文件返回数据的简单服务。

So I am trying to subscribe to a simple service that return data from a local JSON file.

我设法让服务正常工作,我可以在函数中注销它,但是当我在angular 2组件中订阅服务时,它总是未定义的。我不知道为什么?任何帮助将不胜感激。

I have managed to get the service working, I can log it out in the function, but when I subscribe to the service in the angular 2 component, it is always undefined. I'm not sure why? Any help would be much appreciated.

API服务

export class ApiService {
   public data: any;

   constructor(private _http: Http) {
   }

   getData(): any {
       return this._http.get('api.json').map((response: Response) => { 
       console.log('in response', response.json()); //This logs the Object
       this.data = response.json();
       return this.data;
   })
   .catch(this.handleError);
   }
}

组件

export class AppComponent {
   public data: any
   public informationData;

   constructor(private _api: ApiService) {}

   public ngOnInit(): void {
      console.log(this.getDataFromService()); // This return undefined
   }

   public getDataFromService() {
      this._api.getData().subscribe(response => {
          this.informationData = response;
          return this.informationData;
      });
   }
}


推荐答案

也许一些图片有帮助吗?

Maybe some pictures help?

这里的数字表示操作的顺序。

The numbers here indicate the order of operations.

发送Http请求


  1. 组件已初始化并调用getMovies方法movieService。

  2. movieService getMovies方法返回一个Observable。此时不是数据。

  3. 组件在返回的Observable上调用 subscribe

  4. get 请求提交给服务器进行处理。

  5. ngOnInit 方法已完成。

  1. Component is initialized and calls the getMovies method of the movieService.
  2. The movieService getMovies method returns an Observable. NOT the data at this point.
  3. The component calls subscribe on the returned Observable.
  4. The get request is submitted to the server for processing.
  5. The ngOnInit method is complete.

subscribe 之后的任何代码都无法访问电影属性,因为尚未返回数据。

Any code here after the subscribe cannot access the movies property since the data has not yet been returned.

接收Http响应

在某个LATER时间点......

At some LATER point in time ...


  1. 电影将返回服务。

  2. 如果进程成功,则执行第一个回调函数。

  3. 本地电影属性被分配给从服务返回的电影。只有在这里才能最终设置电影属性。

在步骤#8之前尝试访问电影属性会导致错误。

Attempting to access the movies property prior to step #8 results in an error.

我们可以在这里访问该值吗?否

要解决此问题:

这篇关于订阅observable返回undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆