Nuzzob Nuzzob - 4 months ago 8
AngularJS Question

Do things in $http.then(), and then return promise

initUserProfile: function() {

return $http.get('myapi/user/profil').
then(function(response) {
current_user = response.data;
if (current_user.profilpicture) {
current_user.profilpicture = $rootScope.baseURL + "/images/users/" + current_user.username + "/" + current_user.profilpicture;
}
}, function(err) {
// log error
});
};


I want this to return a promise, here it's the case but it's the $http success promise.
How can i do to return a promise when the changes inside the then() are completed ?

Answer

Just return current_user in then() and it will be available as argument of next then() in the chain

initUserProfile: function() {

  return $http.get('myapi/user/profil').
  then(function(response) {
    current_user = response.data;
    if (current_user.profilpicture) {
      current_user.profilpicture = $rootScope.baseURL + "/images/users/" + current_user.username + "/" + current_user.profilpicture;
    }

     return current_user;


  }).catch(function(err) {
    // log error
  });
};

In controller:

myService.initUserProfile().then(function(current_user){
    $scope.user = current_user;
})