【发布时间】:2017-09-16 02:04:17
【问题描述】:
在将 json 响应从 api 转换为 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);
});
【问题讨论】:
-
检查这个问题的接受答案,它解释了你遇到的问题。 stackoverflow.com/questions/22875636/…
标签: typescript casting