请在构造函数中绑定getAll函数,或者您可以使用箭头函数
export class HttpClient {
constructor(url) {
this.url = url;
this.xhr = new XMLHttpRequest();
this.xhr.onloadend = event => {
console.log("ONLOADEND",this.xhr.response);
return this.xhr.result;
};
this.setHeader = this.setHeader.bind(this);
this.get = this.get.bind(this);
this.post = this.post.bind(this);
}
setHeader() {
this.xhr.setRequestHeader("Content-Type","application/json");
}
get(async,header) {
return new Promise((resolve,reject) => {
this.xhr.open("GET",this.url,async);
this.xhr.setRequestHeader(header.name,header.value);
this.xhr.send();
console.log("xhr",this.xhr.response);
resolve(this.xhr.response);
// return nothing
});
}
post(async,data,reject) => {
this.xhr.open("POST",this.url + "create",async);
this.setHeader(header);
this.xhr.send(data);
console.log("RESPONSE",this.xhr.response);
resolve(this.xhr.response);
});
}
}
export class TodoList extends HttpClient {
constructor() {
super("http://todoapp.test/api/");
this.items = [];
this.header = new Headers();
this.header.set("Accept-Encoding","application/json");
this.add = this.add.bind(this);
this.getAll = this.getAll.bind(this);
}
add(todo) {
this.post(true,JSON.stringify(todo),this.header);
this.items.push(todo);
}
getAll() {
this.get(true,this.header).then(result => {
const data = !!result ? result : "[]";
const items = JSON.parse(data);
console.log("result:",result);
items.forEach(item => {
const todo = new Todo(item.id,item.name,item.status);
this.items.push(todo);
});
console.log("items block:",this.items);
});
}
}
本文链接:https://www.f2er.com/3059385.html