无法将 web api 结果绑定到可观察数组 + Knockoutjs

not able to bind web api result to observable array + Knockoutjs

可观察数组未反映绑定网络输出的数据api。因为它反映了绑定硬编码数组的数据。代码函数 GetAllCustomers 有什么问题。

function CustomerDataModel() {

    this.customerList = ko.observableArray([
    { FirstName: "John" },
        { FirstName: "Sam" },
        { FirstName: "Peter" },
        { FirstName: "Vicky"},
        { FirstName: "Amar" }
    ]);        


    this.GetAllCustomers = function () {

        $.ajax({
            url: 'http://localhost/komvc/api/customer',
            type: 'GET',
            dataType: 'json',
            contentType: 'application/json',
            success: function (data) {

                var mappedCusts = $.map(data, function (item) { return { FirstName: item.FirstName }; });
                console.log(mappedCusts[0].FirstName);
                this.customerList = ko.observableArray(this.mappedCusts);
                console.log(JSON.stringify(ko.toJS(this.customerList)));
            },
            error: function (x, y, z) {
                alert(x + '\n' + y + '\n' + z);
            }
        });        
    };
};
ko.applyBindings(new CustomerDataModel());

//html

<div>

    <div data-bind="foreach: customerList">
        <br />
        <span data-bind='text: FirstName' />
    </div>

    <button id="btnGet" data-bind="click:GetAllCustomers">Get All Customers</button>
</div>

//我的网站 api 正在返回

{"Id":1,"FirstName":"Rakesh","LastName":"Suresh","Phone":"919239123","Address":"Bangalore"}

随叫随到:

this.customerList = ko.observableArray(this.mappedCusts);

您正在用破坏 KO 绑定的全新可观察数组覆盖 customerList

您需要做的是更新已经存在的 customerList 为:

this.customerList(mappedCusts);

您还需要修复您的 this 处理,因为在 success 处理程序中 this 肯定不会是您的视图模型对象...

因此您需要在 ajax 调用中使用 context: this, 选项:

$.ajax({
   //...
   context: this,
   success: function (data) {
    //this now refers to the same object as this in GetAllCustomers 
   }
});

或者您可以存储对正确 this 的引用,如下所述:var self = this? or use the bind function,等等

演示 JSFiddle.

顺便说一句,您的 API 正在响应单个对象而不是数组。确保调用正确的 URL 其中 returns 是一个数组,例如:

[{"Id":1,"FirstName":"Rakesh","LastName":"Suresh","Phone":"919239123","Address":"Bangalore"}]