Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Angular TypeError:在尝试调用object.object [].方法时不是函数大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
当我尝试在角度4中@L_675_0@object.object [].方法方法时,我收到以下错误

我的打字稿代码如下.当我@L_675_0@OrderComponent.IncreaseQuantity(itemLoc:number)方法时,当我尝试在方法中@L_675_0@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 @R_835_10586@l: 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.update@R_835_10586@l();
        });

    }

    update@R_835_10586@l(): void {
        this.@R_835_10586@l = 0;
        //console.log("all: " + JSON.Stringify(this.order.orderItems));
        this.order.orderItems.forEach(s => this.@R_835_10586@l += 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解析的对象)上@L_675_0@您的方法.这些对象没有定义那些实例方法方法,这会导致您看到的错误.

相反,你必须做以下事情:

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;

实用函数,构造函数和接口的创造性使用可以用来使上面更简洁,但实质上这是需要的.

大佬总结

以上是大佬教程为你收集整理的Angular TypeError:在尝试调用object.object [].方法时不是函数全部内容,希望文章能够帮你解决Angular TypeError:在尝试调用object.object [].方法时不是函数所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。