簡體   English   中英

angular2-datagrid屬性“ id”在字符串類型中不​​存在

[英]angular2-datagrid property 'id' doesn't exist in type string

我正在嘗試實現angular2-datagrid followig 本教程

我的模特:

export class Inventory{
    active: boolean;
    constructor(public id: number,
        public article: string,
        public description: string,
        public quantity: number,
        public price : string,
        public imgURL: string,
        public createdAt: string,
        public updatedAt: string) {
            this.active = true;
    }
}

我的組件專門在ngOnInit中:

this.getAllInventory();
this.table = new NgDataGridModel<Inventory>([]);
for (let inv in this.allInventories) {
    this.table.items.push(new Inventory(
        inv.id,
        inv.article, 
        inv.description, 
        inv.quantity, 
        inv.price, 
        inv.imgURL, 
        inv.createdAt, 
        inv.updatedAt)
    );
}

this.getAllInventory()是一種稱為Web服務並在for循環中填充allInventories的方法。

這里的方法:

getAllInventory(){
    this.inventoryService.getAllInventory().subscribe(
    data=>{
        console.log(data);
        this.allInventories = data;
    },
    err=>{
        alert ("Error getting inventories");
        console.error(err);
    }
    );
}

這里調用服務的方法,此方法返回清單的json數組:

getAllInventory(){
    var headers = new Headers();
    headers.append("Content-Type", 'application/json');
    headers.append('Authorization', `Bearer ${this.globalVar.getToken()}`);
    var options = new RequestOptions({ headers: headers });
    var result = this.http
       .get(this.globalVar.getHost() + "inventory", options)
       .map((response: Response) => response.json());
    return result;

}

我的錯誤:在de for循環中,對象inv在其屬性中,告訴我:屬性'id'在字符串類型中不​​存在,並且所有屬性均相同。 我該如何解決?

這意味着在Angular 2模型中使用的Inventory內部每個屬性的類型與服務器數據的類型不匹配。

兩種選擇

  1. 修改與Web服務中相同的模型。
  2. 使用以下代碼並強制轉換屬性

    getAllInventory(){this.inventoryService.getAllInventory()。subscribe(data => {console.log(data);讓tempInventory:庫存

      data.forEach((item) => { tempInventory=new Inventory(); tempInventory.id: _.toInteger(item.id), tempInventory.article: item.article.toString(), tempInventory.description: item.description.toString(), tempInventory.quantity: _.toInteger(item.quantity), tempInventory.price : item.price.toString(), tempInventory.imgURL: item.imgURL.toString(), tempInventory.createdAt: item.createdAt.toString(), tempInventory.updatedAt: item.updatedAt.toString() this.allInventories.push(tempInventory); }) console.log(this.allInventories); }, err=>{ alert ("Error getting inventories"); console.error(err); }); } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM