问题
I want to load data from a local .json file and store the content in a local variable, that is accessible throughout the program. I have this function inside my service which I call to get the data.
GetData(){
this.d={Data:[],number:[]}
this.http.get('data.json').map(res =>res.json()).subscribe(res=>
{this.d=(res);
console.log(this.d); //this.d gets the value from res and prints the expected value
});
console.log(this.d);//this.d gets printed as empty
return this.d;
}
this.d seems to get the value from res inside the subscribe portion, but once outside subscribe when I try to print it it seems to be empty. d is declared as an object. What could possibly be the error?
来源:https://stackoverflow.com/questions/39133214/storing-json-data-from-a-file-in-local-variable