NoviceDeveloper NoviceDeveloper - 3 months ago 12
Javascript Question

$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 agnular under the controller where these are, I can see the value of vm.myData and I can pull it too... but I can not seem to assign the data to my vm.view.dataTable.

maybe this is not the right way to do it.

I replaced vm.view.dataTabl with raw json items and it does show.

so something is not working between vm.myData assignment to data;

Answer

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