javascript - Angularjs拦截器导致错误

标签 javascript angularjs

我正在尝试为我的示例 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/

相关文章:

javascript - 如何创建一个列表,使每个选项都是 AngularJS 中的一个列表?

angularjs指令动态设置模板url

javascript - Android - 允许 XMLHttpRequest 到 API 级别 < 16 上的本地文件吗?

javascript - 不一致的 RegEx 空白清理

javascript - 原型(prototype)/脚本切换队列

javascript - angularjs表单发布(使用ngUpload上传文件)和nodejs服务器的跨域问题

javascript - Vue.js 中的电子邮件验证

javascript - 在 Highcharts 中设置动态 x 轴范围

javascript - 无法从 Angular Js 的列表中填充数据

javascript - ngModel - 如何处理它在不同浏览器中的不同行为?