在$ http.then()中执行操作,然后返回promise

时间:2016-07-21 17:09:20

标签: javascript angularjs promise angular-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
  });
};

我希望这会返回一个承诺,在这种情况下,这是$ http成功承诺。 当then()内的更改完成后,如何返回一个promise?

2 个答案:

答案 0 :(得分:2)

只需在current_user中返回then(),它就可以作为链中下一个then()的参数

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

在控制器中:

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

答案 1 :(得分:0)

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