如何用承诺返回的数组替换 knockout js 可观察数组的内容

How do I replace the contents of knockout js observable array with an array returned from a promise

我正在尝试用从 promise 返回的数组替换可观察数组的内容。

我像这样初始化一个可观察数组

let contents = ko.observableArray([]);

从 promise 返回的数组看起来像这样

[{name : test, code : 0, country : UK}]

如何用从 promise 返回的数组内容替换空的可观察数组?

我试过了

promise.then(array => {contents(array)});

还有这个

promise.then(function(value){contents(value)})

但他们都没有向可观察数组中添加任何东西。

勾选这个link

您应该首先通过名为 removeAll 的 observableArray 方法删除其内容(如果有)。

// empty the array
contents.removeAll()

// insert the new array values
promise.then(array => {ko.utils.arrayPushAll(contents, array)});

// or
promise.then(function(value){ko.utils.arrayPushAll(contents, value)});