Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 角度:模块'中混合提供程序和自定义服务;s配置/运行_Javascript_Angularjs_Angularjs Service - Fatal编程技术网

Javascript 角度:模块'中混合提供程序和自定义服务;s配置/运行

Javascript 角度:模块'中混合提供程序和自定义服务;s配置/运行,javascript,angularjs,angularjs-service,Javascript,Angularjs,Angularjs Service,我想做这样的事情: angular.module('app', []).config( [ '$httpProvider', 'customAuthService', ($httpProvider, customAuthService) -> $httpProvider.defaults.transformRequest.push (data) -> if customAuthService.isLoggedIn data[

我想做这样的事情:

angular.module('app', []).config(
  [ '$httpProvider', 'customAuthService',
    ($httpProvider, customAuthService) ->
      $httpProvider.defaults.transformRequest.push (data) ->
        if customAuthService.isLoggedIn
          data['api_key'] = {token: @token}
  ])
根据,我不能在我的
模块的
config
块中执行此操作,因为那里不允许使用自定义服务,也不能在
run
块中执行此操作,因为那里不允许使用
$httpProvider
等提供程序:

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

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


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

据我所知,您可以将其注入配置中的函数。如果请求没有使用我的身份验证服务登录,我会使用类似的方法来拦截请求

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

始终可以在回调函数中获取注入器,然后获取服务实例(“服务定位器”样式,而不是在配置函数中注入依赖项)

我想在特殊情况下是可以的,尽管广泛使用它并不好看

.config([ '$httpProvider', function($httpProvider)  {
    $httpProvider.defaults.transformRequest.push(function(data) {

        var $injector = angular.injector(['app']);
        var customAuthService = $injector.get('customAuthService');

        // ...
      });
  }])
但是,与其这样做

您看过文档中的响应拦截器了吗


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

不起作用,读取请求转换器的方法需要回调,而不是数组,因此我得到了
类型错误:对象不是函数。
。我最终配置了
$http
,而不是
$httpProvider
,就我的用例而言,它提供了完全相同的值。谢谢。有没有办法使用
angular.injector
并获得与调用
config(…)
方法的模块相同的服务实例?