我有这种代码:
spear.ts:
export class Spears {
constructor(
id: string = null,
transaction_id: string = null,
spear_id: number = null,
delivery_date: any = null,
delivery_time: any = null,
...
) {}
}
稍后,我在我的component.ts类中使用该类,并且该类将分配有从后端获取的数据
spear.component.ts:
export class CpCoorPenerimaanSpearDetailComponent implements OnInit {
spear = new Spears();
spearForm = new Spears();
constructor() { }
ngOnInit() {
this._spears.getSpearDetail().subscribe(
res => {
this.spear = res.data;
this.spearForm = res.data;
}
err => console.log(err);
);
}
}
每次我都想使用对象的值时,它总是显示错误消息,指出对象类型的对象不存在。例如,当我想在执行spearForm = res.data
之后立即console.log属性时,它只显示如下消息:
Property 'spear_id' does not exist on type 'Spears'.
我已经为这个问题苦苦挣扎了5个小时。我一直在寻找类似的问题,它说只是将属性的类型更改为任何。事件只是控制台记录了数字类型的spear_id,它表示属性不存在。
让我最困惑的是有时不显示该消息,但是当我感觉一切正常后,该消息又显示了。有什么帮助吗?
答案 0 :(得分:0)
在正确的位置定义类属性
export class Spears {
id: string;
transaction_id: string;
spear_id: number;
delivery_date: any;
delivery_time: any;
constructor(data) {
this.id = data['id'] || null;
this.transaction_id = data['transaction_id'] || null;
// map every field
}
}
然后
this._spears.getSpearDetail().subscribe(
res => {
this.spear = res.data;
this.spearForm = new Spears(res.data);
}
err => console.log(err);
);
希望这会有所帮助!