0

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;
};
aregawi
  • 3
  • 3
  • Looks like you are getting confused about Promises. Best to find a quick tutorial and learn about the difference in styles between Callbacks and Promises. – Zack Argyle Nov 08 '14 at 00:21

1 Answers1

0

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

E.g., 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);
    }
);
Community
  • 1
  • 1
niklr
  • 1,671
  • 3
  • 24
  • 40