AngularJS发布成功回调甚至在错误时触发

时间:2015-03-24 06:36:15

标签: angularjs

为什么响应为500时会在此处触发成功回调?

$scope.submit = function() {
    var user = $scope.user;
    // provide username and password to obtain a token which will be used for api calls
    $http.post('/authenticate', user).
        success(function(data, status, headers, config) {
            $window.sessionStorage.token = data.token;
            $location.path('/');
        }).
        error(function(data, status, headers, config) {
            $scope.errors = data.errors;
            $scope.message = 'Invalid JSON format, see guidelines for correct format';
            $scope.uploadError = true;
            console.log('ERROR TRUE');
        });
};

拦截器:

angular.module('uploadApp')
       .factory('authInterceptor',

function ($rootScope, $q, $window, $location) {
  return {
    request: function (config) {
      config.headers = config.headers || {};
      if ($window.sessionStorage.token) {
        config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
      }
      return config;
    },
    response: function (response) {
      return response || $q.when(response);
    },
    responseError: function(response) {
      if (response.status === 401) {
         $location.path('/login');

      }
      return response || $q.when(response);
    }
  };
});

1 个答案:

答案 0 :(得分:2)

angular $q承诺工作的方式是错误需要处理不当以继续沿着错误路径 - 否则它假定您已纠正问题或处理错误。因此,最简单的方法是throw来自错误路径的响应,直到达到您实际想要处理它的程度。

angular.module('uploadApp')
   .factory('authInterceptor',

function ($rootScope, $q, $window, $location) {
  return {
    request: function (config) {
      config.headers = config.headers || {};
      if ($window.sessionStorage.token) {
        config.headers.Authorization = 'Bearer ' +
            $window.sessionStorage.token;
      }
      return config;
   },
   response: function (response) {
     return response || $q.when(response);
   },
   responseError: function(response) {
     if (response.status === 401) {
       $location.path('/login');
     }
     // instead of returning, you should throw, 
     // and when you throw you don't need to wrap, as it will
     // handle it for you.
     //return response || $q.when(response);
     throw response;
   }
  };
});

$q将确保抛出的对象包含在promise调用链中。请注意,每当您返回$q承诺时,它将假定您已处理任何问题,除非您抛出而不是返回。这允许您在调用链中进一步向下解析器中出现错误,然后可将其视为错误。

如果投掷不是你的风格,你可以推迟一个新的承诺并返回它,然后拒绝它 - 但这比使用当前的调用链效率低。