这里是新手(第一个 angular2 天)
我有一个包含 3 个字段的类:id
和 name
传递给构造函数,第三个字段称为 data
应该接收JSON文件的内容
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();
}
}
然后我像这样实例化对象
new Hero("hero1", "Hero 1");
问题是指令 this.data = result;
不会工作,因为 this
指的是请求对象,而不是类。
另外,我不知道这是否是继续(以及获取 json 文件)的正确方法。我仍然迷失在 angular2 中。谢谢
最佳答案
改用箭头函数
request.onload = () => {
var result = JSON.parse(this.responseText);
this.data = result;
};
关于javascript - angular2 - 将 json 文件内容放入我的类属性中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38505741/