Reputation: 147
I am working on a project in Angular6, where I need to make a HTTP call to fetch JSON data. The call is correct (I have checked the output in console). The problem is that my function in Service is returning 'undefined' befire the HTTP call finishes. But the 'undefined' is returned and all the rest of my functions in component are throwing me an error.
menuService.ts
getCall(url, options) {
this.http.get(url, options).subscribe(
(data:any) => {
if(data){
console.log(data);
return data;
},
error => {
return [];
}
);
}
menu.ts
getCall(url, options) {
let result: any;
result = this.menuSvc.getCall(url, options);
let l:number = result.length; //error is thrown here, "no length property for 'undefined'
return result;
}
I have searched the web and found solutions like Promise(); but i didn't really understand on how to apply it. It would be great if someone could help. Thanks!
Upvotes: 0
Views: 40
Reputation: 5602
You are not returning anything. In service, it should return an observable which should be subscribed by the caller.
Change your code like this:
menuService.ts
getCall(url, options) {
return this.http.get(url, options);
}
menu.ts
getCall(url, options) {
let result: any;
this.menuSvc.getCall(url, options)
.subscribe(result => {
console.log(result);
//do whatever you want to do with result.
});
}
Upvotes: 2