Reputation: 5241
I'd like to do somtehing like that:
angular.module('app', []).config(
[ '$httpProvider', 'customAuthService',
($httpProvider, customAuthService) ->
$httpProvider.defaults.transformRequest.push (data) ->
if customAuthService.isLoggedIn
data['api_key'] = {token: @token}
])
According to Angularjs doc, I can't do it in the config
block of my module
, because custom services are not allowed there, nor can I do it in the run
block, because providers like $httpProvider
aren't allowed there:
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.
How can I do to add some configuration in my $httpProvider
that relies on a home-made service ?
Upvotes: 5
Views: 4282
Reputation: 6062
It is always possible to get an injector and then the instance of the service inside the callback function ('service locator' style as opposed to having the dependency injected in the config function).
I guess is ok for exceptional cases, although not pretty to use it extensively.
.config([ '$httpProvider', function($httpProvider) {
$httpProvider.defaults.transformRequest.push(function(data) {
var $injector = angular.injector(['app']);
var customAuthService = $injector.get('customAuthService');
// ...
});
}])
But, instead of doing that...
Have you looked at Response interceptors in the $http documentation?
It looks better suited for authentication purpouses and you can get the service injected there.
Upvotes: 7
Reputation: 12059
You can inject it to functions inside of your config as far as I know. I use something similar to intercept requests if they aren't logged in using my auth service.
.config(['$httpProvider',function ($httpProvider) {
var authRequest= ['customAuthService', function(customAuthService) {
if(customAuthService.isLoggedIn){
data['api_key'] = {token: @token};
}
}];
$httpProvider.defaults.transformRequest.push(authRequest);
}]);
Upvotes: 0