简体   繁体   中英

AngularJS - return promise success value to the calling function

I am learning AngularJS and AJAX.I am trying to assign the data being returned by the success function to user. grantRole belongs to Auth service. The value of user as I currently have it is a promise. How do I assign the returned data on success to user?

$scope.grantRole = function(user) {

  user = Auth.grantRole(user).then(
    function success(data){
        return data;
    },
    function error(err){
        console.log(err);
    }
 );

grantRole: function(user,callback) {
      var cb = callback || angular.noop;
      var data = {id: user._id,controller:'role'};
       return User.update({id: user._id,controller:'role'},data,
          function(user) {
            return cb(user);
          }, function(err) {
            return cb(err);
          }).$promise;
};

The current value of user being a promise is correct. Once the promise gets resolved, it will be assigned to the data returned on success.

But you have to be careful when reassigning objects or arrays. See Service variable not updating in controller

Eg, don't do this: user = ...;

Rather, do this: angular.copy(newInfo, user) or this: user.email = ...

$scope.grantRole = function(user) {

  Auth.grantRole(user).then(
    function success(data){
        angular.copy(data, user);
    },
    function error(err){
        console.log(err);
    }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM