我正在尝试为我的示例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");
}
}
});
它在我的控制台中显示“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);
答案 0 :(得分:2)
请遵循以下代码方法:
var interceptor = function ($q, $location) {
return {
response: function (result) {
console.log(result);
return result;
}
}
};
angular.module('app', [])
.config(function ($httpProvider) {
$httpProvider.interceptors.push(interceptor);
});