Just starting out with Angular 2 (first day!)
I'm working on a class that has 3 fields: id
and name
which are passed to the constructor, and a third field called data
which should hold the content of a JSON file.
export class Hero {
id: string;
name: string;
data: Object;
constructor(id: string, name: string) {
this.id = id;
this.name = name;
//retrieve JSON and assign it to this.data
var request = new XMLHttpRequest();
request.onload = function(){
var result = JSON.parse(this.responseText);
this.data = result;
};
//get the json file based on the object's id
request.open("get", id+".json", true);
request.send();
}
}
Then I create an instance of the object like this
new Hero("hero1", "Hero 1");
The issue is that the instruction this.data = result;
doesn't work because this
refers to the request object, not the class itself.
Also, I'm not sure if this is the correct approach (or even how to properly fetch the JSON file). I'm still pretty confused in my Angular 2 journey. Thanks!