I am writing a code in Angular where the JSON response (array of JSON) from a REST call needs to be displayed as a table on GUI. The JSON format is not pre-defined and I need to capture in in some generic format and then use it. The piece of code is as follows:
getResultsFromDB() {
this.http.get('app/api/locSearchReq.json').subscribe(
data => {
**this.locResults = data as any;**
},
(err: HttpErrorResponse) => {
console.log (err.message);
}
);
console.log('Data ' + this.locResults);
}
If I move console.log call within subscribe, it prints the retrieved data. But I am not able to access this.locResults outside the subscribe call or outside the function.
Other similar functions which I have written, where I am receiving pre-defined Json array as response and is mapped to a typescript class, I am able to access the data outside the function.
getResultItems() {
this.http.get(this.glResultItems).subscribe(
data => {
this.resultItems = data as ResultItem [];
},
(err: HttpErrorResponse) => {
console.log (err.message);
}
);
}
When I try to access this.resultItems outside the function, I am able to do so. I am not able to understand what am I doing wrong or different here,
Data in locSearch.json is as follows:
[{
"name": "sookshm",
"age": "27",
"org": "abc",
"location": "NJ",
"expertise": "javascript"
}, {
"name": "Liu",
"age": "35",
"org": "ibm",
"location": "NJ",
"expertise": "css"
}, {
"name": "Mike",
"age": "38",
"org": "msn",
"location": "NY",
"expertise": "html"
}]
In browser console it shows this.locResults as undefined.
Need help with paring/handling this response.