1

I see the following example for calling a server-side resource:

UserSession.prototype.$save = function() {
    return $http.post('/users/sign_in', {
      "user" : { 
        "email" : this.email,
        "password" : this.password,
        "remember_me" : this.remember_me ? 1 : 0 
      }   
    }); 
  };  

My question is, is it possible to see the actual error response in this code in the event the call fails? How would the above get written for that?

0

3 Answers 3

4

You missed the callbacks

UserSession.prototype.$save = function() {
    return $http.post('/users/sign_in', {
      "user" : { 
        "email" : this.email,
        "password" : this.password,
        "remember_me" : this.remember_me ? 1 : 0 
      }   
    })
    .success(function (data, status, headers, config) {
       // success logic here
    })
    .error(function (data, status, headers, config) {
       // error logic here
    });
}; 
Sign up to request clarification or add additional context in comments.

Comments

2

You need to use the .error() callback Reference

   UserSession.prototype.$save = function() {
        return $http.post('/users/sign_in', {
          "user" : { 
            "email" : this.email,
            "password" : this.password,
            "remember_me" : this.remember_me ? 1 : 0 
          }   
        }).error(function(data, status, headers, config) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
        });
  };  

Comments

1

You can define the .success and .error callbacks in that function like the other answers suggest, but I feel it is more likely you would want the application code that is calling the .$save to determine what gets done on success or fail.

So you would leave the .$save function as is, and everywhere in your application you call myUserSession.$save(), you can just do:

myUserSession.$save()
   .success(function(data, httpStatus, header, config) {
       ...
   })
   .error(function(data, httpStatus, header, config) {
       ...
   });

Doing this just makes the code a little bit more reusable. Of course if you know for a fact on save you want the exact same behaviour everywhere, then just go with what the other answers suggest.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.