2017-08-03 49 views
2

当我尝试调用object.object []。方法中角度4的方法时出现以下错误:Angular TypeError:尝试调用object.object []方法时不是函数。方法

OrderComponent.html:30 ERROR TypeError: item.increaseQuantity is not a function at 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; 
    } 

} 

回答

3

你从来没有任何实例或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; 

创造性地使用的效用函数,构造函数和接口可以用来渲染上面更简洁,但在本质上,这是需要什么。

+1

谢谢你 - 解决问题。 – tazza

相关问题