如何在angularAMD配置选项中注入拦截器服务

时间:2016-02-17 20:14:12

标签: angularjs requirejs interceptor angular-amd

我正在使用带有require js的angularAMD,我已经编写了一个拦截器服务,我想在我的app配置文件中注册$ httpProvider.interceptors但是它会抛出错误

  

错误:[$ injector:unpr]   http://errors.angularjs.org/1.4.8/ $注射器/ unpr?P0 = cookieInjectorProvider%... eInjector%20%3 C-%20%24http%20%3 C-%20%24templateRequest%20%3 C-%20%24compile(...)

以下是我的意见

define(["angularAMD", "angular-route", "ui-bootstrap","ngCookies","common/service/interceptor-service"], function(angularAMD){
"use strict";

var app = angular.module("app", ["ui.router", "ui.bootstrap","ngAnimate","ngTouch","angular-carousel","ngCookies"]);

  //route
  app.config(["$stateProvider", "$urlRouterProvider", "$locationProvider","$httpProvider", function($stateProvider, $urlRouterProvider, $locationProvider,$httpProvider){
    $urlRouterProvider.otherwise('/');

    $stateProvider
    .state("home", angularAMD.route({

     url: "/",
     views:  {  

       'header':{
          /*...*/
        },

      },
      'content': {
        /*...*/
      },

      'footer': {
        /*...*/

      }
  }));
  **//angular is not able to find 'cookieInjector' service**
  $httpProvider.interceptors.push('cookieInjector');
  }]);


  // Bootstrap Angular when DOM is ready
  return angularAMD.bootstrap(app, false, document.getElementsByTagName("body")[0]);
});

和我的“cookieInjector文件是”这项服务需要另一项服务,它也以类似的方式实施

    define([
  'angularAMD',
  "common/service/cookie-service"
  ], function(angularAMD){
    angularAMD.service("cookieValidator",[function(){
      this.isLoggedIn = false;
      this.getIsLoggedIn = function(){
          return this.isLoggedIn;
      };
      this.setIsLoggedIn = function(status){
          this.isLoggedIn = status;
      };  
    }])
    .factory('cookieInjector', ['$q','cookieValidator', 'cookieService',function($q,cookieValidator,cookieService) {
      var cookieInjector = {
        request: function(config) {
          var cookie = cookieService.getCookie();
          if(!cookie){
            cookieValidator.setIsLoggedIn(false);
            //$location.path('/login');
          }else{
            cookieValidator.setIsLoggedIn(true);
          }
            config.headers['Token'] = cookie ? cookie : null;
            return config;
        },
        response: function(response) {
            response.config.responseTimestamp = new Date().getTime();
            return response;
        },
        responseError: function(response) {
            // Cookie has expired
            if(response.status === 401 || response.status === 403) {
              cookieService.destroyCookie();
              cookieValidator.setIsLoggedIn(false);
            }
            return $q.reject(response);
        }
    };
    return cookieInjector;
  }]);
})

我完全陷入困境。谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

  

angular无法找到'cookieInjector'服务

这可能是因为app.config运行时cookieInjector不可用。我记得angularAMD.factory()只会在app.config()运行后将您的工厂/服务投放到您的应用中。

因此,在这种情况下,应使用另一个全局角度模块,而不是使用angularAMD

创建文件 cookieInjector.js

angular.module('cookieModule', []).facotry('cookieInjector', ['$q', 'cookieValidator', 'cookieService', function($q, cookieValidator, cookieService) {
    var cookieInjector = {
        request: function(config) {
            var cookie = cookieService.getCookie();
            if (!cookie) {
                cookieValidator.setIsLoggedIn(false);
                //$location.path('/login');
            } else {
                cookieValidator.setIsLoggedIn(true);
            }
            config.headers['Token'] = cookie ? cookie : null;
            return config;
        },
        response: function(response) {
            response.config.responseTimestamp = new Date().getTime();
            return response;
        },
        responseError: function(response) {
            // Cookie has expired
            if (response.status === 401 || response.status === 403) {
                cookieService.destroyCookie();
                cookieValidator.setIsLoggedIn(false);
            }
            return $q.reject(response);
        }
    };
    return cookieInjector;
}]);

然后init可以配置你的应用程序。

// requireJS config
requirejs.config({
    path:{
        cookieInjector: 'path/to/cookieInjector'
    }
    // ... your codes

    shim: {
        // ... your codes
        // make sure cookie injector only load after angularJS is loaded.
        cookieInjector: ["angular"];
    }
});

// your app.js (?) file
define(["angularAMD", "cookieInjector", "angular-route", "ui-bootstrap", "ngCookies", "common/service/interceptor-service"], function(angularAMD) {
    "use strict";

    var app = angular.module("app", ["cookieModule", "ui.router", "ui.bootstrap", "ngAnimate", "ngTouch", "angular-carousel", "ngCookies"]);

    //route
    app.config(["$stateProvider", "$urlRouterProvider", "$locationProvider", "$httpProvider", function($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider) {
        $urlRouterProvider.otherwise('/');

        $stateProvider
        .state("home", angularAMD.route({

            url: "/",
            views: {

                'header': {
                    /*...*/
                },

            },
            'content': {
                /*...*/
            },

            'footer': {
                /*...*/

            }
        })); 
        // It should be loaded now
        $httpProvider.interceptors.push('cookieInjector');
    }]);


    // Bootstrap Angular when DOM is ready
    return angularAMD.bootstrap(app, false, document.getElementsByTagName("body")[0]);
});