Joseph Seraphi
Joseph Seraphi

Reputation: 3

Angular's $http post method

So I have the following method in my app:

self.addUser = function() {
  var errCode;
  $http.post('users/add', {username: self.username, password: self.password}).
    success(function(data, status, headers, config) {
      // this callback will be called asynchronously
      // when the response is available
      var errCode = data.errCode;
      if(errCode == -2) {
        alert("Error: This username already exists.");
      }
      else if(errCode == -3) {
        alert("Error: The username is empty, too long, or has invalid characters.");
      }
      else if(errCode == -4) {
        alert("Error: The password is empty, too long, or has invalid characters.");
      }
      else {
        alert("User created.");                     
      }
      console.log(errCode);
      return errCode;
    }).
    error(function(data, status, headers, config) {
      // called asynchronously if an error occurs
      // or server returns response with an error status.
      alert("Error.");
    });
    console.log(self.username);
  }

Our backend is set up to return a JSON object, data, which contains an errCode (among other things) that's equal to 1 on a successful save, and a negative number of something goes wrong.

My goal is to get errCode outside of this function.

It appears that the function inside $http has its own scope, and I can't find a way to get errCode outside this function even if, for example, I declare a $scope variable outside the function and try to update it inside the function. How should I do this?

EDIT: I haven't fixed the problem yet, but the issue that was tripping me up was that I had forgotten that this works asynchronously (which both Mukund and isim elaborate on).

EDIT: ANSWERED

Upvotes: 0

Views: 119

Answers (2)

Sebastian Piu
Sebastian Piu

Reputation: 8008

As $http returns a promise I would suggest you return that promise to the caller of addUser. You could define it like this;

addUser: function() {
     var promise = $http.post(......).then(function(response) {
          //error handling and stuff
          //return the data
          return response.data.errCode;
     });

     //return the promise to the caller
     return promise;
}

then in the code that uses this you can keep nesting then to do what you need.

//somewhere in your controller
someObject.addUser().then(function(errCode) {
     //do something with the error
});

Another way would be to send a callback as an argument to your addUser function:

addUser: function(callback) {
     $http.post(......).then(function(response) {
          //error handling and stuff
          //return the data
          callback(response.data.errCode);
     });
}

//in your controller
someObject.addUser(function(errorCode){
    //do something with errCode
});

but the first method is cleaner in my opinion

Upvotes: 2

Mukund Kumar
Mukund Kumar

Reputation: 23201

replace above code with following code:

self.addUser = function() {
        var errCode;
        $http.post('users/add', {username: self.username, password: self.password}).
            success(function(data, status, headers, config) {
            // this callback will be called asynchronously
            // when the response is available
                var errCode = data.errCode;
                self.retrieveErrCode(errCode);
                if(errCode == -2) {
                    alert("Error: This username already exists.");
                }
                else if(errCode == -3) {
                    alert("Error: The username is empty, too long, or has invalid characters.");
                }
                else if(errCode == -4) {
                    alert("Error: The password is empty, too long, or has invalid characters.");
                }
                else {
                    alert("User created.");                     
                }
                console.log(errCode);
                $scope.errCode=errCode //you can either use this line or below line
                return errCode;
            }).
            error(function(data, status, headers, config) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
                alert("Error.");
            });
            console.log(self.username);

    }

in your case you are returning error code before the success block execution(because callback function execute later when data fetch from database.so it take some time.but your function retun errCode that is undefined before success block execution)

Upvotes: 0

Related Questions