Angular:在模块's的config/run中混合了提供商和自定义服务

Angular: Mixing provider and custom service in module's config/run

本文关键字:混合 run 提供商 服务 自定义 config 模块 Angular      更新时间:2023-09-26

我想这样做:

angular.module('app', []).config(
  [ '$httpProvider', 'customAuthService',
    ($httpProvider, customAuthService) ->
      $httpProvider.defaults.transformRequest.push (data) ->
        if customAuthService.isLoggedIn
          data['api_key'] = {token: @token}
  ])

根据Angularjs文档,我不能在moduleconfig块中这样做,因为那里不允许自定义服务,我也不能在run块中这样做,因为那里不允许$httpProvider这样的提供商:

配置块 -在提供程序注册和配置阶段执行。只有提供程序和常量可以注入到配置块中。这是为了防止服务在完全配置之前意外实例化。

运行块 -在注入器创建后执行,用于启动应用。只有实例和常量可以注入到运行块中。这是为了防止在应用程序运行时进行进一步的系统配置。

如何在我的$httpProvider中添加一些依赖于自制服务的配置?

总是有可能先获得一个注入器,然后在回调函数中获得该服务的实例('服务定位器'风格,而不是在config函数中注入依赖项)。

我想在特殊情况下是可以的,尽管不太适合广泛使用。

.config([ '$httpProvider', function($httpProvider)  {
    $httpProvider.defaults.transformRequest.push(function(data) {
        var $injector = angular.injector(['app']);
        var customAuthService = $injector.get('customAuthService');
        // ...
      });
  }])

但是,不是那样做…

你看过$http文档中的响应拦截器吗?

它看起来更适合于身份验证目的,您可以在那里注入服务。

据我所知,你可以将它注入到配置中的函数中。我使用类似的东西拦截请求,如果他们没有使用我的认证服务登录。

.config(['$httpProvider',function ($httpProvider) {
    var authRequest= ['customAuthService', function(customAuthService) {
       if(customAuthService.isLoggedIn){
           data['api_key'] = {token: @token};
       }  
    }];
    $httpProvider.defaults.transformRequest.push(authRequest);
}]);