Angularjs拦截器无法正常工作

时间:2015-05-13 05:20:22

标签: angularjs angular-http angular-http-interceptors

我正在尝试创建一个看起来像这样的$http拦截器:

.config(['$httpProvider',function($httpProvider){
$httpProvider.interceptors.push(function($q,$window){
    return {
        'request':function(config){
            config.headers = config.headers || {};
            if($window.sessionStorage)
                config.headers.Authorization = 'Bearer '+$window.sessionStorage.token;
        },
        'requestError':function(rejection)
        {
            $q.reject(rejection);
        },
        'response':function(response){
            return response || $q.when(response);
        },
        'responseError':function(response)
        {
            if(response!=null && response.status == 401)
            {
                delete $window.sessionStorage.token;
                //make the user login again
            }
            return response || $q.when(response);   
        }       
    };
});
}])

拦截器因错误而失败:

 TypeError: Cannot read property 'headers' of undefined
at serverRequest (angular.js:9366)
at processQueue (angular.js:13248)
at angular.js:13264
at Scope.$eval (angular.js:14466)
at Scope.$digest (angular.js:14282)
at Scope.$apply (angular.js:14571)
at bootstrapApply (angular.js:1455)
at Object.invoke (angular.js:4203)
at doBootstrap (angular.js:1453)
at bootstrap (angular.js:1473)

2 个答案:

答案 0 :(得分:3)

您忘记返回public class StudentRepository extends UserRepositoryImpl<Student> { public Class getType() { return Student.class; } } 值...

config

来自documentation

  

request: function(config) { if ($window.sessionStorage) { config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token; } return config; } :使用http配置对象调用拦截器。该函数可以自由修改配置对象或创建一个新对象   函数需要直接返回 request对象,或包含config或新config对象的承诺。

答案 1 :(得分:2)

我建议使用工厂并确保将header对象设置为对象:

angular.module('app')
  .factory('AuthInterceptor', ["$window", "$q", function ($window, $q) {

    return {
        request: function (config) {
            config.headers = config.headers || {};
            if ($window.sessionStorage) {
               config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
            }
            return config;
        },
        responseError: function (response) {
            if(response != null && response.status == 401)
            {
                delete $window.sessionStorage.token;
                //make the user login again
            }
            return response || $q.when(response);
        }
    }
  }]);

并在您的配置部分中使用:

$httpProvider.interceptors.push("AuthInterceptor");