Reputation: 157
I have initialized array of objects and pushed another empty array inside it, I want this nested array to be updated right after getting data from an API. I am getting data in console but there is nothing happening at HTML side. I think this is because when I push empty array HTML is initialized as empty and when data is updated it is not binding data from nested Array.
I have tried it like this:
var dummy_data = {
nested_array: ko.observableArray()
};
function IndexViewModel()
{
var self = this;
self.main_array = ko.observableArray([]);
};
// I want to push at start, because there are so many API calls and I don't
// want user to wait until all data is loaded.
globalpointer.main_array.push(dummy_data);
fetch("/SomeRoute").then(x => {
x.json().then(b => {
dummy_data.nested_array = b;
});
});
var globalpointer = new IndexViewModel()
ko.applyBindings(globalpointer);
HTML is:
<!-- ko foreach:main_array() -->
<!-- ko foreach:nested_array() -->
<div data-bind='text:name'>
</div>
<!-- /ko -->
<!-- /ko -->
I am expecting to get name
in HTML, but I got nothing! Although I can see it in console when I write:
globalpointer.main_array()[0].nested_array
It displays all the info in nested_array
.
Upvotes: 2
Views: 146
Reputation: 3788
This replaces the observable array in nested_array
with the parsed result of json()
, which is not an observable array:
x.json().then(b => {
dummy_data.nested_array = b;
})
Assuming that your fetch
result parses to an array, then you would want to do this:
x.json().then(b => {
dummy_data.nested_array(b);
})
Upvotes: 2