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;
});
}
}
SubscribinglinkAn Observable instance begins publishing values only when someone subscribes to it. You subscribe by calling the subscribe() method of the instance, passing an observer object to receive the notifications.
Subscriptions to observables are quite similar to calling a function. But where observables are different is in their ability to return multiple values called streams (a stream is a sequence of data over time). Observables not only able to return a value synchronously, but also asynchronously.
Subscribing to an Observable is like calling a function, providing callbacks where the data will be delivered to. This is drastically different to event handler APIs like addEventListener / removeEventListener . With observable.subscribe , the given Observer is not registered as a listener in the Observable.
How to access value outside the . subscribe in angular 2 polling service. After the first execution of your subscribe-method the variable is set. If the value is required in other functions I suggest you to call them from within your subscribe, because otherwise you cannot be sure when your http-request is finished.
Maybe some pictures help?
The numbers here indicate the order of operations.
Send the Http Request
subscribe
on the returned Observable.get
request is submitted to the server for processing.ngOnInit
method is complete.Any code here after the subscribe
cannot access the movies
property since the data has not yet been returned.
Receive the Http Response
At some LATER point in time ...
Attempting to access the movies property prior to step #8 results in an error.
Can we access the value here? NO
To fix it:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With