I'm new to angular2 and am attempting to map a JSON response to an array of custom objects. The strange behavior I am seeing is when I attempt to access a variable with an underscore in it, I receive a compile error. I modeled after the Tour of Heroes code.
My Object is:
export class EventCount {
event_count: number;
name: string;
id: string;
}
To match the JSON response sample:
[{"event_count":10,"name":"dev-03","id":"0001"},
{"event_count":6,"name":"dev-02","id":"0002"}]
My http.get request looks like:
getEventCounts(): Observable<Array<any>> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
let query = this.getEventCountURL;
return this.http.get(query, options)
.map(this.extractCounts)
.catch(this.handleError);
}
And the function called within the map looks like:
private extractCounts(response: Response) {
if (response != null) {
try {
let myCounts = response.json() as EventCount[];
for (let entry of myCounts) {
console.log("Name: " + entry.name + ", id: " + entry.id );
}
} catch (e) {
console.error(e.toString());
}
}
return myCounts;
}
The above code works fine and I receive the correct output in the console log.
Name: dev-03, id: 0001
Name: dev-02, id: 0002
However when I change the log to the following:
console.log("Name: " + entry.name + ", count: " + entry.event_count );
I get a compile error:
ERROR in .../count.service.ts: Property 'event_count' does not exist on type 'EventCount'.
In the VSCode debugger I can clearly see that the event_count variable within the entry object is getting populated when I am not using it in the log printout.
Thoughts or ideas? Thanks in advance!
EventCountclass. TO test, I changedevent_counttoeventcountandevent_count2and continues to work (also hard refreshed the browser + restarted npm). Now I am able to print the value incount.service.tslike I wanted before; I'm not exactly sure where the snag was. Thanks for the pointers on the GET request. - aspergillusOryzae