Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 258
ejoubaud Avatar asked May 07 '13 03:05

ejoubaud


1 Answers

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.

like image 155
garst Avatar answered Nov 14 '22 23:11

garst