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
Subscribe to observable is returning undefined
提问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.
这里的数字表示操作的顺序。
- Component is initialized and calls the getMovies method of the movieService.
- The movieService getMovies method returns an Observable. NOT the data at this point.
- The component calls
subscribeon the returned Observable. - The
getrequest is submitted to the server for processing. - The
ngOnInitmethod is complete.
- 组件被初始化并调用movieService 的getMovies 方法。
- movieService getMovies 方法返回一个 Observable。不是此时的数据。
- 组件调用
subscribe返回的 Observable。 - 该
get请求被提交给服务器进行处理。 - 该
ngOnInit方法完成。
Any code here after the subscribecannot access the moviesproperty since the data has not yet been returned.
由于尚未返回数据,因此此处之后的任何代码subscribe都无法访问该movies属性。
At some LATER point in time ...
在稍后的某个时间点......
- The movies are returned to the service.
- If the process was successful, the first callback function is executed.
- The local movies property is assigned to the movies returned from the service. It is only here that the movies property is finally set.
- 电影将返回给服务。
- 如果过程成功,则执行第一个回调函数。
- 本地电影属性被分配给从服务返回的电影。只有在这里最终设置了电影属性。
Attempting to access the movies property prior to step #8 results in an error.
在第 8 步之前尝试访问电影属性会导致错误。
回答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();
})


