AngularJS - 将$ http拦截器放在单独的文件中

时间:2016-11-13 00:33:31

标签: angularjs http angular-http-interceptors

如何将拦截器放在单独的文件中并将其推送到配置块中的$ httpProvider中。

这是我目前的配置块:

(function() {
  'use strict';

  angular
    .module('app')
    .config(config);

  config.$inject = ['$httpProvider'];

  function config($httpProvider) {
    $httpProvider.defaults.withCredentials = true;
    $httpProvider.defaults.useXDomain = true;
    $httpProvider.interceptors.push(['$injector', '$q', function($injector, $q) {
      return {
        responseError: function(response) {
          var toastr = $injector.get('toastr');
          var lodash = $injector.get('lodash');
          toastr.error(lodash.get(response, 'data.message', 'Alguma coisa deu errado.'));
          if (response.status !== 401) {
            return $q.reject(response);
          }

          var userService = $injector.get('userService');
          if (userService.isLogged()) {
            userService.logout();
          }

          var $state = $injector.get('$state');
          $state.go('login');
          return $q.reject(response);
        }
      };
    }]);
  }
})();

1 个答案:

答案 0 :(得分:0)

使用{ 'Vincent van Gogh': [ ('Cafe Terrace at Night', '1888', '81.0', '65.5', 'oil paint', 'Netherlands'), ('Self-Portrait with Bandaged Ear', '1889', '51.0', '45.0', 'oil paint', 'USA') ], 'Pablo Picasso': [ ('Guernica', '1937', '349.0', '776.0', 'oil paint', 'Spain') ], 'Leonardo da Vinci': [ ('Mona Lisa', '1503', '76.8', '53.0', 'oil paint', 'France'), ("Portrait of Isabella d'Este", '1499', '63.0', '46.0', 'chalk', 'France'), ('The Last Supper', '1495', '460.0', '880.0', 'tempera', 'Italy') ] } 内的代码创建工厂,并将该工厂推送到拦截器集合。

return {.....}