I recently started working with angular2 and I'm trying to map a JSON response to an array of custom objects. The issue I'm facing is that when I try to access a variable with an underscore in its name, I encounter a compile error. I followed the Tour of Heroes example for guidance.
Here's my custom object:
export class EventCount {
event_count: number;
name: string;
id: string;
}
To match the sample JSON response:
[{"event_count":10,"name":"dev-03","id":"0001"},
{"event_count":6,"name":"dev-02","id":"0002"}]
My http.get request method looks like this:
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);
}
The function called within the map is as follows:
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 code above works perfectly fine and I can see the correct output in the console log.
Name: dev-03, id: 0001
Name: dev-02, id: 0002
However, when I change the logging line to:
console.log("Name: " + entry.name + ", count: " + entry.event_count );
I receive 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 populated even when it's not being used in the log output.
Any thoughts or suggestions? Appreciate the help!