点击处理程序中的打字稿和错误的类型

时间:2018-10-19 12:33:38

标签: typescript knockout-3.0

我的TypeScript

2018-10-09-12:00

我的HTML:

export class CustomerUIModel implements CustomerIntrerfaces.ICustomerUI {

    public customers: KnockoutObservableArray<CustomerIntrerfaces.ICustomer>;
    service: CustomerIntrerfaces.ICustomerService;



    constructor(svc: CustomerIntrerfaces.ICustomerService, data: CustomerIntrerfaces.ICustomer[]) {
        this.service = svc;
        this.customers = ko.observableArray(data);
    }

    public AddCustomer(elem: CustomerIntrerfaces.ICustomer): void {
        this.service.Insert(elem)
            .then(cRes => {
                this.customers.push(elem);
            })
            .catch(r => {
                alert(r.message);
            });
    }
}}

当我单击“插入”时,我进入AddCustomer(),但 this.service customers 都是NULL。此外,“此”具有一个CustomerIntrerfaces.ICustomer,而不是我期望的CustomerIntrerfaces.ICustomerService。我该如何解决?

1 个答案:

答案 0 :(得分:1)

看来,淘汰赛未在您想要的AddCustomer上下文中调用this方法。参见this thread。您可以通过绑定以下方法来强制this上下文成为您的CustomerUIModel对象:

public AddCustomer = (elem: CustomerIntrerfaces.ICustomer): void => {
    this.service.Insert(elem)
        .then(cRes => {
            this.customers.push(elem);
        })
        .catch(r => {
            alert(r.message);
        });
}

有关一般问题的更多信息,请参见this FAQ