Search code examples
javascriptangularjsangularjs-scopedom-events

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


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(...);