0

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?

4
  • 1
    is there a reason you are using xmlhttp and not $http? Commented Mar 8, 2016 at 19:17
  • 1
    Use the AngularJS $http service to do XHRs. docs.angularjs.org/api/ng/service/$http Commented Mar 8, 2016 at 19:19
  • getTestUser method doesn't return anything so nothing is assigned. But as above comments suggest, you should use $http and return a promise Commented Mar 8, 2016 at 19:23
  • ah, maybe that is what I was missing. Thanks for the replies! I'm looking into the $http Commented Mar 8, 2016 at 20:07

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.