Javascript 订阅 observable 返回 undefined

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46769042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:36:56  来源:igfitidea点击:

Subscribe to observable is returning undefined

javascriptangulartypescriptobservableangular2-services

提问by Sam Kelham

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

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

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.

我已经设法使服务正常工作,我可以在函数中将其注销,但是当我在 angular 2 组件中订阅该服务时,它始终未定义。我不确定为什么?任何帮助将非常感激。

API service

接口服务

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

Component

成分

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

回答by DeborahK

Maybe some pictures help?

也许一些图片有帮助?

The numbers here indicate the order of operations.

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

Send the Http Requestenter image description here

发送 Http 请求在此处输入图片说明

  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 subscribeon the returned Observable.
  4. The getrequest is submitted to the server for processing.
  5. The ngOnInitmethod is complete.
  1. 组件被初始化并调用movieService 的getMovies 方法。
  2. movieService getMovies 方法返回一个 Observable。不是此时的数据。
  3. 组件调用subscribe返回的 Observable。
  4. get请求被提交给服务器进行处理。
  5. ngOnInit方法完成。

Any code here after the subscribecannot access the moviesproperty since the data has not yet been returned.

由于尚未返回数据,因此此处之后的任何代码subscribe都无法访问该movies属性。

Receive the Http Responseenter image description here

接收 Http 响应在此处输入图片说明

At some LATER point in time ...

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

  1. The movies are returned to the service.
  2. If the process was successful, the first callback function is executed.
  3. The local movies property is assigned to the movies returned from the service. It is only here that the movies property is finally set.
  1. 电影将返回给服务。
  2. 如果过程成功,则执行第一个回调函数。
  3. 本地电影属性被分配给从服务返回的电影。只有在这里最终设置了电影属性。

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

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

Can we access the value here? NOenter image description here

我们可以访问这里的值吗?不在此处输入图片说明

To fix it:enter image description here

要解决这个问题:在此处输入图片说明

回答by Antoine Clavijo

You've got a problem between sync and async function. You'r issue is: getDateFromServiceis syncronous and the content inside is async. So when the ngOnInitfunction call getDataFromService, you'r code don't wait the async task. you'r getDataFromServiceneed to return an observer or need to implement the return of your API (you need to choose).

您在同步和异步功能之间遇到了问题。你的问题是:getDateFromService是同步的,里面的内容是异步的。因此,当ngOnInit函数调用时getDataFromService,您的代码不会等待异步任务。您getDataFromService需要返回一个观察者或需要实现您的 API 的返回(您需要选择)。

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

public getDataFromService() {
  return this._api.getData();
}

回答by mehul

objResponse;
this.service.getData().subscribe((result: any)=> { 
this.objResponse=result;
}

Returning something won't required

不需要退货

回答by dips

Instead of logging at the ngOnInit() method as you did

而不是像你那样登录 ngOnInit() 方法

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

log inside the subscribe() method as

在 subscribe() 方法中登录为

export class AppComponent {
  public data: any
  public informationData;

  constructor(private _api: ApiService) {}

  public ngOnInit(): void {
    this.getDataFromService(); //don't log here, logging here will return undefined
  }

  public getDataFromService() {
    this._api.getData().subscribe(response => {
      this.informationData = response;
      console.log(this.informationData); //log here, like this
      return this.informationData;
    });
  }
}

回答by mayank arora

you can do it like this:

你可以这样做:

In your app-component:

在您的应用程序组件中:

public getDataFromService() {
  this._api.getData(this);
}


public setData(data: any){
 this.data=data;
}

In your service/api.ts:

在您的服务/api.ts 中:

public getData(obj: appComponentModel){
    this.http.get(url).subscribe(res => obj.setData(res));
}

回答by Amit

Try with:

尝试:

getData(): any {
       return this._http.get('api.json');
}

or

或者

   getData(): any {
           return this._http.get('api.json').map((response: Response) => { 
    response.json();
})