micahhoover
micahhoover

Reputation: 2160

jQuery Ajax with Ionic / Cordova

I have a service that uses full-blown jQuery to request JSON info from a service on the interwebs.

I have confirmed from the Chrome console that the data I need is being returned, but the response is picked up after the Ionic/Angular controller returns.

// inside controller:
$scope.days = Calendar.all();
// all() grabs a null object that hasn't been populated from AJAX result yet

Here's the all method in the service:

   return {
    all: function() {
      return days;
    },
    ...
  };

So the controller always has an empty object when it should have the contents of the ajax response.

This is in the service constructor:

  var days = {}; // makes it empty

  $.get("https://jsonblob.com/api/5544b86z_edited_3aef9ba", function(data, status){

        var result = data;    // Object {Month: "August", Year: "2015", Online: "true", Days: Array[31]}
        days = result.Days;
  });

So $scope.days stays at {};

What is the best way to pass the results into the controller object?

EDIT:

Tried the $http approach, but got: "$http is not defined" ... even after I commented out the full-blown jQuery reference in my index.html. (Got the answer here)

Upvotes: 0

Views: 7098

Answers (1)

shaunhusain
shaunhusain

Reputation: 19748

You should just use the $http service it'll trigger an $apply for you so the view updates once the results come back, and the $http methods will return a promise that you can use to check in the script when the result comes back instead of a callback.

Just inject $http into your service (the top level function of the service)

then change your code to:

return $http.get("https://jsonblob.com/api/5544b86z_edited_3aef9ba")
.then(function(response){
  var result = response.data;
  days = result.Days;
});

https://docs.angularjs.org/api/ng/service/$http

It's likely that days should be a property of the service itself as well so you can inject the service into a controller set a reference to it on the scope and then show it in the view.

Alternatively you can have your service method return the result of the .then call which will be another promise then in the controller you could do:

Calendar.all.then(function(response){
  $scope.days = response.data;
});

The promise is basically an alternative way to handle async operations that replaces the need for a regular callback because the promise object stores any functions you pass to then and triggers them when the result comes back. The .then method of the promise actually takes two functions optionally first a success callback then an error callback, see the promise documentation for details.

Upvotes: 4

Related Questions