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

查看:39
本文介绍了订阅 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;
      });
   }
}

推荐答案

也许一些图片有帮助?

此处的数字表示操作顺序.

The numbers here indicate the order of operations.

发送 Http 请求

  1. 组件已初始化并调用 movieService 的 getMovies 方法.
  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 之后的任何代码都无法访问 movies 属性,因为数据尚未返回.

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

接收 Http 响应

在以后的某个时间点......

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天全站免登陆