i have a function in my angular 2 project
this.fetchedData= this._visitService.getchartData().toPromise();
console.log("WORKING I HOPE0", this.fetchedData)`
which gives the output:
WORKING I HOPE0
ZoneAwarePromise {__zone_symbol__state: null, __zone_symbol__value: Array(0)}
__zone_symbol__state:true
__zone_symbol__value:Array(2)
0:{date: "2018, 03, 14", value: 11}
1:{date: "2018, 03, 15", value: 1}
length:2
__proto__:Array(0)
__proto__:Object`
Is it possible to access __zone_symbol__value
to get it whole as an object or even just retrieve data from it. I tried using console.log("WORKING I HOPE0", this.fetchedData.__zone_symbol__value)
but it doesn't seem to work. I am not looking for any alternate way of doing it. So if I wanted to know if its possible or not and why or why not.
I think you should do it like :
this._visitService.getchartData().toPromise().then(data => {
this.fetchedData = data;
console.log(data);
})
For your queries as per the comment , try this :
this._visitService.getchartData().toPromise().then(data => {
this.fetchedData = data;
console.log(data);
this.processFetchedData(); // call the function once this.fetchedData is initialized
})
processFetchedData(){
console.log(this.fetchedData); // check the console
}
Since you want to know 'why' aspect:- You have to first wait for the promise to resolve. In the resolving function's success handler, you will get the data. Right now, the "fetchedData" variable stores the promise, it will have only Promise specific functionality and "NOT" the actual data. Upon its resolve, as below, you can retrieve the data and do the required parsing.
Actual code which will work is the one given by @Vivek Doshi above, using the 'then' function.
You can add specific success/failure handlers as follows (if u want it separately):-
var promise = serviceCall.toPromise();
promise.success( (data) => this.fetchedData = data );
promise.error( (err) => console.log(err.message) );
A Promise handles a single event when an asynchronous operation completes or fails.
You should wait for the promise to resolve, so this is what you need:
this._visitService.getchartData().toPromise()
.then(response => {
this.fetchedData = response;
console.log(response);
})
.catch(error => { console.log(error) });
If your response comes from an http call:
this._visitService.getchartData().toPromise()
.then(response => {
var json = response.json();
this.fetchedData = json;
console.log(json);
})
.catch(error => { console.log(error) });
I encountered the same issue as I've been refactoring code to use async/await, and in this occasion forgot to prefix the function call with await.
Adding in e.g.
async MyFunction() {
this.fetchedData = await this._visitService.getchartData().toPromise();
}
may do the trick, if this was your intention (it was, in my case).
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