gpt4 book ai didi

Angular 类型错误 : is not a function when trying to call an object. 对象 []. 方法

转载 作者:太空狗 更新时间:2023-10-29 17:48:07 26 4
gpt4 key购买 nike

当我尝试在 Angular 4 中调用 object.object[].method 的方法时出现以下错误:

OrderComponent.html:30 ERROR TypeError: item.increaseQuantity is not a function at OrderComponent.increaseQuantity (order.component.ts:87)

我的 typescript 代码如下。当我调用 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;
}

}

最佳答案

您永远不会实例化任何 OrderOrderItem 实例。只是在做

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;

创造性地使用效用函数、构造函数和接口(interface)可以使上述内容更加简洁,但本质上,这是需要的。

关于 Angular 类型错误 : is not a function when trying to call an object. 对象 []. 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45474538/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com