John Lee
John Lee

Reputation: 1387

Using an Angular Service for async HttpRequests - how to callback?

I might be totally confused on how to properly use callback methods for ajax calls in angular. I have the following angular app and cannot figure out how to display the testUser object only after the ajax call is successfully completed.

I have an ng controller like so:

Controllers.controller('mainController', ['$scope','UserService', function ($scope, UserService) {
   ...
   $scope.testUser = UserService.getTestUser();
   ...
}

The UserService is defined like so:

 Services.service('UserService', function () {
   ...
   this.getTestUser = function() {
     ...
     var xmlhttp = new XMLHttpRequest();
     xmlhttp.onreadystatechange = function() {
       if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
         return JSON.parse(xmlhttp.responseText);
       }
     };
     xmlhttp.open('GET',url,false);   //async set to false
     xmlhttp.send();
   }
   ...
 }

Currently, the $scope.testUser is 'undefined' and blank on the page because it is being displayed before the ajax call completes. You can see in my service function that I have async set to false, but it doesnt seem to matter.

I've confirmed the ajax call does eventually return a populated user object. What am I missing to make the page display $scope.testUser only when its been successfully retrieved?

Upvotes: 0

Views: 119

Answers (1)

John Lee
John Lee

Reputation: 1387

Thanks to Slava and georgeawg. I changed to the following and everything works great!

Controllers.controller('mainController', ['$scope','UserService', function ($scope, UserService) {
 ...
 UserService.getTestUser.async().then(function(testUser) {
   $scope.testUser = testUser; 
 };
 ...
}

And on the service side I have this:

Services.service('UserService', function ($http) {
...
this.getTestUser = {
  async: function() {
     var promise = $http.get(url).then(function(response) {
       return response.data;
     };
     return promise;
  }
}

Thank you!

Upvotes: 1

Related Questions