gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 06:07:14 25 4
gpt4 key购买 nike

我想做这样的事情:

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

根据 Angularjs doc , 我不能在我的 moduleconfig block 中执行此操作,因为那里不允许自定义服务,我也不能在 run 中执行此操作code> block ,因为那里不允许像 $httpProvider 这样的提供程序:

Configuration blocks - get executed during the provider registrations and configuration phase. Only providers and constants can be injected into configuration blocks. This is to prevent accidental instantiation of services before they have been fully configured.

Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.

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

最佳答案

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

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

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

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

// ...
});
}])

但是,与其那样做...

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

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

关于javascript - Angular : Mixing provider and custom service in module's config/run,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16410769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com