0

Hello I am using ngResource $save method and I get two different behaviours, I don't understand why

First I'm using it in this way:

    $scope.user = new User($scope.user);
    $scope.user.$save(function () {
       $window.location.href = //redirection here;
    }, function (response) {
        $scope.form.addErrors(response.data.errors);
    });

Then I have another controller when I'm doing a similar operation, but even getting 404 or 422 errors from the server the first callback is executed and the errors callback is ignored.

Does anyone have any idea of this? I've been searching in Google for hours trying to find more documentation about $save but I'm still stuck with this problem.

Thank you.

Farzad
  • 842
  • 2
  • 9
  • 26
Duilio
  • 258
  • 1
  • 10
  • Im guessing that your `$scope.user` object varies from location to location, resulting in one call having an error. What's the console say – tymeJV Apr 07 '14 at 15:49
  • It throws the 422 error as expected (because 1 field was invalid but only on backend validation), but then it executes the first callback... I am reusing the same controller for different templates and different forms, could it be the reason? – Duilio Apr 07 '14 at 16:26
  • Shouldn't be the issue - each instance of the controller will create it's own scope. The error handler may only fire for certain status codes, try returning just a `401`? – tymeJV Apr 07 '14 at 18:16
  • Yeah, it redirects me to the login page, but only because I'm using an interceptor, I just commented the interceptor and now the $save method sucessfully calls the error callback, so the problem is on the interceptor. – Duilio Apr 07 '14 at 18:35
  • here is the interceptor, I guess I have to do something else instead of just returning the response: myApp.config(function ($httpProvider) { $httpProvider.interceptors.push(function($window) { return { 'responseError': function(response) { if (response.status == 401) { // Unathorized $window.location.href = 'index.html'; } return response; } }; }); }); – Duilio Apr 07 '14 at 18:36

1 Answers1

0

Well, the problem was on an interceptor I am using to detect 401 (unauthorized errors)

here is the interceptor, notice that you must return $q.reject(response) otherwise the other callbacks are not called (in my case the error callback in ngResource.$save)

MyApp.config(function ($httpProvider) {
    $httpProvider.interceptors.push(function($window, $q) {
        return {
            'responseError': function(response) {
                if (response.status == 401) { // Unathorized
                    $window.location.href = 'index.html';
                }
                // return response; <-- I was doing this before cancelling all errors
                return $q.reject(response);
            }
        };
    });
});
Duilio
  • 258
  • 1
  • 10