When attempting to call a method of an object.object[].method in Angular 4, I encountered the following error:
Error Message: OrderComponent.html:30 ERROR TypeError: item.increaseQuantity is not a function at OrderComponent.increaseQuantity (order.component.ts:87)
The TypeScript code that triggers this error is as follows. The issue arises when trying to call this.orderItems[itemLoc].increaseQuantity() inside the OrderComponent.IncreaseQuantity(itemLoc: number) method. It is puzzling why it does not recognize the OrderItem.increaseQuantity method:
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;
}
}