javascript – 拦截器不工作

前端之家收集整理的这篇文章主要介绍了javascript – 拦截器不工作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在AngularJS中制作一个拦截器.我是AngularJS的新手,并且发现了一些拦截器的例子,但是不能让它工作.

这里有我的app.js文件,它们都有相关的代码.我还有一个控制器调用REST api并返回JSONP.

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

使用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);
    });
  };
});

解决方法

$httpProvider.responseInterceptors已被弃用.您可以修改代码
app.factory('errorInterceptor',['$q','$rootScope','MessageService','$location',$rootScope,$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');    
}]);

有关更多信息,请参阅Docs

原文链接:https://www.f2er.com/js/154954.html

猜你在找的JavaScript相关文章