Angular TypeError:在尝试调用object.object [].方法时不是函数
发布时间:2020-12-17 17:33:31 所属栏目:安全 来源:网络整理
导读:当我尝试在角度4中调用object.object [].方法的方法时,我收到以下错误: OrderComponent.html:30 ERROR TypeError: item.increaseQuantity is not a function at OrderComponent.increaseQuantity (order.component.ts:87) 我的打字稿代码如下.当我调用Order
当我尝试在角度4中调用object.object [].方法的方法时,我收到以下错误:
我的打字稿代码如下.当我调用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; } } 解决方法
您永远不会实例化任何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; 实用函数,构造函数和接口的创造性使用可以用来使上面更简洁,但实质上这是需要的. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |