$http.get gets deseralized JSON but can't assign it to array

Issue

I have a problem reading data into another variable, I have this function:

var vm = this;

$http.get("/source").success(function(data) {
     alert("Horay !!!");
     vm.myData = data;
}).error(function() {
     alert("Dang It!");
});

And then I have the following:

vm.view = {
    dataTable:  vm.myData,
    order: {
        classification: 'lastname',
        orderby: '+'
    }
};

Using angular under the controller where these are, I can see the value of vm.myData and I can pull it too, but I cannot seem to assign the data to my vm.view.dataTable.

Maybe this is not the right way to do it?

I replaced vm.view.dataTable with raw JSON items and it does show,
so something is not working between vm.myData assignment to data.

Solution

$http.get is asynchronous. vm.dataTable is assigned to undefined and only then vm.myData is assigned to data.

It should be

$http.get("/source").success(function(data) {
  vm.myData = data;
  vm.view.dataTable = data
}).error(...);

success is deprecated. It can be replaced with

$http.get("/source").then(function(response) {
  vm.myData = response.data;
  vm.view.dataTable = response.data
}).catch(...);

Answered By – Estus Flask

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published