So I am trying to subscribe to a simple service that return data from a local JSON file.
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 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;
});
}
}
getDataFromService
doesn't itself return anything. Change.subscribe
to.map
and return the resulting observable, then use| async
to resolve it in the template. – DaggettSubscription
object. i.e if you return the function call itself. – Owensbythis.informationData = response;
,return this.informationData;
? – Islingtonreturn this.informationData;
its why I asked why you need to return from subscribe? – Owensbyreturn this.informationData;
as it is already been assigned to the variable? Thank you for all this – Islington