2

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.

2
  • 2
    dummy_data.nested_arra(b); did u try this. = voilates 2 way binding data stays in object it wont bind to view. Commented Jul 8, 2019 at 10:17
  • Tried but didn't worked Commented Jul 9, 2019 at 6:42

1 Answer 1

2

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);
 })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.