从类api到类型转换类的类型转换json响应后,我无法访问该类的方法。Typescript - 在没有创建类的新实例的情况下在类中转换默认方法
class Stock {
name: String;
purchaseDate: Date;
constructor() {}
convertDates() {
this.purchaseDate = new Date(this.purchaseDate);
}
}
getAll() {
return this.http.get(URL + '/find').map(
(response) => {
this.stocks = response as Array<Stock>;
_.forEach(this.stocks, (stock) => {
stock.convertDates();
}
},
(error) => {
this.stocks = [];
}
);
}
我如下得到一个错误信息: “stock.convertDates不是一个函数”。 如果我通过响应中的所有股票列表循环并在调用“convertDates”方法之前为每个股票创建一个实例,则此工作原理没有任何错误。下面是它的代码:
_.forEach(response, (stock) => {
let newstock = new Stock();
_.merge(newstock, stock);
newstock.convertDates();
this.stocks.push(newstock);
});
查看关于此问题的接受答案,它解释了您遇到的问题。 https://stackoverflow.com/questions/22875636/how-do-i-cast-a-json-object-to-a-typescript-class – supersighs