javascript 拦截器不工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21269007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 20:31:37  来源:igfitidea点击:

Interceptor not working

javascriptangularjsinterceptorangular-http-interceptors

提问by olefrank

Im trying to make a Interceptor in AngularJS. I'm quite new to AngularJS and found some examples of Interceptor, but can't get it to work.

我试图在 AngularJS 中制作一个拦截器。我对 AngularJS 很陌生,发现了一些拦截器的例子,但无法让它工作。

Here I have my app.js file, which have all relevant code. I also have a controller which calls a REST api and get JSONP returned.

这里有我的 app.js 文件,其中包含所有相关代码。我还有一个控制器,它调用 REST api 并返回 JSONP。

First I declare the module and then config it (define the Interceptor). It should now catch all requests and output to console...

首先我声明模块,然后配置它(定义拦截器)。它现在应该捕获所有请求并输出到控制台...

Is it wrong to create the Interceptor with app.factory?

使用 app.factory 创建拦截器是错误的吗?

var app = angular.module(
    'TVPremieresApp',
    [
    'app.services'
      , 'app.controllers'
    ]
);

app.config(function ($httpProvider) {
    $httpProvider.responseInterceptors.push('errorInterceptor');
});

app.service('MessageService', function () {
    // angular strap alert directive supports multiple alerts. 
    // Usually this is a distraction to user. 
    //Let us limit the messages to one    
    this.messages = [];
    this.setError = function(msg) {
        this.setMessage(msg, 'error', 'Error:');
    };
    this.setSuccess = function(msg) {
        this.setMessage(msg, 'success', 'Success:');
    };
    this.setInfo = function (msg) {
        this.setMessage(msg, 'info', 'Info:');
    };    
    this.setMessage = function(content, type, title) {
        var message = {
            type: type,
            title: title,
            content: content
        };
        this.messages[0] = message;
    };
    this.clear = function() {
        this.messages = [];
    };
});

app.factory('errorInterceptor', function ($q, $location, MessageService, $rootScope) {
    return function (promise) {
    // clear previously set message
    MessageService.clear();

    return promise.then(function (response) {
      console.log(response);
      return response;
    }, 
    function (response) {
      if (response.status == 404) {
        MessageService.setError('Page not found');
      } 
      else if(response.status >= 500){
        var msg = "Unknown Error.";

        if (response.data.message != undefined) {
          msg = response.data.message + " ";
        }
        MessageService.setError(msg);
      }
      // and more
      return $q.reject(response);
    });
  };
});

回答by Satpal

$httpProvider.responseInterceptorsare deprecated. You can modify your code

$httpProvider.responseInterceptors已弃用。你可以修改你的代码

app.factory('errorInterceptor', ['$q', '$rootScope', 'MessageService', '$location',
    function ($q, $rootScope, MessageService, $location) {
        return {
            request: function (config) {
                return config || $q.when(config);
            },
            requestError: function(request){
                return $q.reject(request);
            },
            response: function (response) {
                return response || $q.when(response);
            },
            responseError: function (response) {
                if (response && response.status === 404) {
                }
                if (response && response.status >= 500) {
                }
                return $q.reject(response);
            }
        };
}]);

app.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push('errorInterceptor');    
}]);

See Docsfor more info

查看文档了解更多信息