Nuzzob
Nuzzob

Reputation: 411

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 ?

Upvotes: 1

Views: 2598

Answers (2)

Maciej Sikora
Maciej Sikora

Reputation: 20132

    initUserProfile: function ()
    {

    var defer=$q.defer();

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

                    //here resolve
                    defer.resolve();

                    }else{
                     defer.reject();
                    }


                }, function (err) {
                    // log error
                    defer.reject();
                });


    //retun promise
    return defer.promise;
    };

Upvotes: 0

charlietfl
charlietfl

Reputation: 171679

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;
})

Upvotes: 2

Related Questions