pumpkinzzz pumpkinzzz - 4 months ago 55
AngularJS Question

angular2 - get json file content into my class attribute

newbie here (first angular2 day)

I have a class with 3 fields:

id
and
name
which are passed to the constructor, and a third field called
data
which should receive 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 according to the object id
request.open("get", id+".json", true);
request.send();

}
}


then i instantiate the object like this

new Hero("hero1", "Hero 1");


The problem is that instruction
this.data = result;
won't work because
this
refers to the request object, not the class.

Plus, i don't know if this is the correct way to proceed (and to get the json file). I'm still quite lost in angular2. Thanks

Answer

Use arrow function instead

    request.onload = () => {
        var result = JSON.parse(this.responseText);
        this.data = result;
    };