我正在尝试为我的示例 angular.js 应用程序创建一个拦截器。这是我的配置代码:
.config(function ($routeProvider, $httpProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
$httpProvider.interceptors.push('failedRequestInterceptor');
});
和我的拦截器
angular.module('sandboxApp').factory('failedRequestInterceptor', function ($q) {
return {
'response': function (config) {
console.log("test");
}
}
});
它在我的控制台中显示“测试”字符串,但之后我立即收到错误“响应未定义”并且应用程序无法加载。
也许这与使用 yeoman 及其附带的工具有关,这是来自控制台的确切错误文本:
Error: response is undefined handleRequestFn/<@http://localhost:9000/bower_components/angular/angular.js:16002:11 processQueue@http://localhost:9000/bower_components/angular/angular.js:13137:27 scheduleProcessQueue/<@http://localhost:9000/bower_components/angular/angular.js:13153:27 $RootScopeProvider/this.$get</Scope.prototype.$eval@http://localhost:9000/bower_components/angular/angular.js:14353:16 $RootScopeProvider/this.$get</Scope.prototype.$digest@http://localhost:9000/bower_components/angular/angular.js:14169:15 $RootScopeProvider/this.$get</Scope.prototype.$apply@http://localhost:9000/bower_components/angular/angular.js:14457:13 done@http://localhost:9000/bower_components/angular/angular.js:9614:36 completeRequest@http://localhost:9000/bower_components/angular/angular.js:9804:7 requestLoaded@http://localhost:9000/bower_components/angular/angular.js:9745:1
返回 logFn.apply(console, args);
最佳答案
请遵循以下代码方法:
拦截器功能:
var interceptor = function ($q, $location) {
return {
response: function (result) {
console.log(result);
return result;
}
}
};
拦截器注入(inject):
angular.module('app', [])
.config(function ($httpProvider) {
$httpProvider.interceptors.push(interceptor);
});
关于javascript - Angularjs拦截器导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27470578/