How to finish executing $http.get first before running any code in angular

1.9k views Asked by At

I have this method in my service to get a user

getUser : function () {
  console.log("get user");
  token = authService.getToken();
  userID = jwtHelper.decodeToken(token);

  console.log(token);
  console.log(userID);

  return $http.get(httpHost + '/users/' + userID).success(function (data) {
     user = data;
     console.log(user);
     return data;
  });
  },

I ran this service in .run of angular Then in my controller I'm getting the data so to present the user's name in my view
$scope.userName = userService.getFirstName() + " " + userService.getLastName();.
It will run well most of the time, but there are times that when there is a delay in getting the user the controller will be executed first leaving the $scope.username with undefined values.
How can I make my program to wait for the getUser() to return the user's data first before running the controller??

2

There are 2 answers

0
Devin H. On BEST ANSWER

$http.get returns a promise. So what you can do is whenever you call getUser is do:

service.getUser().then(function(response){ //stuff you need to do on finish here });
4
twitch On
You need to use $q services
.ABCController($scope,$http,$q){
getUser : function () {
  var deferred = $q.defer();
  console.log("get user");
  token = authService.getToken();
  userID = jwtHelper.decodeToken(token);

  console.log(token);
  console.log(userID);

  return $http.get(httpHost + '/users/' + userID).success(function (data) {
     user = data;
     console.log(user);
     deferred.resolve(user)
     return deferred.promise;
  });
  },