pumpkinzzz pumpkinzzz - 1 year ago 187
AngularJS Question

angular2 - get json file content into my class attribute

newbie here (first angular2 day)

I have a class with 3 fields:

which are passed to the constructor, and a third field called
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);


then i instantiate the object like this

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

The problem is that instruction
this.data = result;
won't work because
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 Source

Use arrow function instead

    request.onload = () => {
        var result = JSON.parse(this.responseText);
        this.data = result;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download