当我尝试在角度4中调用object.object []。方法的方法时,我收到以下错误:
OrderComponent.html:30 ERROR TypeError:item.increaseQuantity不是a 功能 在OrderComponent.increaseQuantity(order.component.ts:87)
我的打字稿代码如下。当我调用OrderComponent.IncreaseQuantity(itemLoc:number)方法时,当我尝试在方法中调用this.orderItems [itemLoc] .increaseQuantity()方法时,它会生成上面的错误。我不知道为什么它不知道OrderItem.increaseQuantity方法:
import { Component, Inject } from '@angular/core';
import { Http } from '@angular/http';
class OrderItem {
id: number;
name: string;
unitPrice: number;
quantity: number;
amount: number;
comment: string;
increaseQuantity(): boolean {
console.log("In the Order Item itself - worked.");
this.quantity += 1;
this.amount = this.quantity * this.unitPrice;
return false;
}
}
class Order {
id: number;
createdTime: Date;
orderType: string;
tableName: string;
orderItems: OrderItem[];
}
@Component({
selector: 'order',
templateUrl: './order.component.html'
})
export class OrderComponent {
public order: Order;
public total: number = 0;
constructor(http: Http, @Inject('ORIGIN_URL') originUrl: string) {
http.get(originUrl + '/api/Order/2').subscribe(result => {
this.order = result.json() as Order;
this.updateTotal();
});
}
updateTotal(): void {
this.total = 0;
//console.log("all: " + JSON.stringify(this.order.orderItems));
this.order.orderItems.forEach(s => this.total += s.amount);
}
increaseQuantity(itemLoc: number): boolean {
//item.increaseQuantity();
let item = this.order.orderItems[itemLoc] as OrderItem;
console.log("This increaseQuantity work." + JSON.stringify(item));
return item.increaseQuantity();
//return false;
}
}
答案 0 :(得分:6)
您永远不会实例化任何Order
或OrderItem
个实例。刚做
this.order = result.json() as Order
或
let item = this.order.orderItems[itemLoc] as OrderItem;
不会导致自动创建这些实例,因此您最终会在纯数据对象(即从JSON解析的对象)上调用您的方法。这些对象没有定义那些实例方法方法,这会导致您看到的错误。
相反,你必须做类似的事情:
const orderData = result.json();
const order = new Order();
order.id = orderData.id;
// ... assign rest of properties
order.items = orderData.orderItems.map(orderItemData => {
const orderItem = new OrderItem();
orderItem.id = orderItemData.id;
// ... assign rest of properties
return orderItem;
});
this.order = order;
实用函数,构造函数和接口的创造性使用可以用来使上面更简洁,但实际上这是需要的。