'对象'类型上不存在属性'对象的属性'

问题描述 投票:0回答:1

我有这样的代码:

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);
    );
  }
}

每次我想使用对象的值时,它总是显示错误消息,即对象的属性不存在Object类型。例如,当我想在执行spearForm = res.data之后的console.log属性时,它只显示如下消息:

Property 'spear_id' does not exist on type 'Spears'.

我一直在努力解决这个问题5个小时。我找了类似的问题,它说只是将属性的类型更改为任何。事件只是控制台记录了数字类型的spear_id,它表示属性不存在。

让我困惑最多的是有时候信息没有显示,但是在我感觉一切顺利之后,再次显示消息。有什么帮助吗?

angular typescript
1个回答
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);
);

希望这会有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.