【发布时间】:2018-09-30 00:48:56
【问题描述】:
当我使用 httpClient 获取一个对象数组时,我可以访问数组中每个对象的属性,但我无法访问方法。我不明白为什么,我该怎么做。
this.interventionService.getInterventions().subscribe(interventions =>
{
interventions.forEach(it => {
console.log(it.InterventionId); // property can be accessed
console.log(it.myMethod()); // myMethod cannnot be accessed
// I get an error: 'myMethod is not a function'
});
});
但是,如果我创建一个新对象,我可以访问这些方法:
var it = new Intervention();
it.myMethod(); // no error
感谢您的帮助
【问题讨论】:
-
Intervention的接口是什么? -
还有
getInterventions()的实现是什么? -
你需要类似:
... .getInterventions().map(items => items.map(i => new Intervention(i)).subscribe ... -
对模型使用接口而不是类。将方法放入服务中。
-
您必须手动将您的对象映射到您的类。 Angular httpClient 只是将数据解析为对象。它对你的方法一无所知
标签: angular