How to inject service to angular constant

11,135

Solution 1

You can manually grab $locale with the $injector. Observe the following...

app.constant('SOME_CONSTANT', { 
    'LOCALE': angular.injector(['ng']).get('$locale').id.slice(0, 2) 
});

JSFiddle Example

Solution 2

this is not possible for two reasons.

  1. constant can not have dependencies (see table bottom https://docs.angularjs.org/guide/providers)

  2. constants and provider are available in .config functions (config phase), but services ($locale) are available only later (in .run function/phase)

Alternatively you can create service-type factory, which can have dependencies and can create object or primitive

angular.module('app')
  .factory('LOCALE_ID', function($locale) {
      return {'LOCALE': $locale.id.slice(0, 2)}
  })
Share:
11,135
ciembor
Author by

ciembor

Updated on June 14, 2022

Comments

  • ciembor
    ciembor almost 2 years

    I would like to define a constant which use $locale service. Constants are objects, so I can't inject it as parameter as in case of controller. How can I use it?

    angular.module('app').constant('SOME_CONSTANT', {
      'LOCALE': $locale.id.slice(0, 2)
    })
    
  • milanlempera
    milanlempera almost 9 years
    I am not sure if is good ideal call angular.injector inside module code. Typical using is cooperation with third part libraries. I think this is angular services live cycle workaround
  • scniro
    scniro almost 9 years
    Seems fine to me. Can you give some definitive reason as to why this would not be a good idea? Don't agree with the downvote, OP is satisfied with the answer
  • milanlempera
    milanlempera almost 9 years
    Question is "How to inject service to angular constant" and general, answer is nowise. In special use case (here inject service from ng module) is it possible but, i think your solutions goes against the purpose of DI. DI says show your dependencies and here you are loading value from global dependency. (docs says inject is for "access to the injector from outside Angular" ) Moreover angular constants (by definition) can not have dependencies. They are formed in a different step of lifecycle (see my post and documentation link). Therefore, I think that your answer is not good.
  • scniro
    scniro almost 9 years
    angular.injector states - "Creates an injector object that can be used for retrieving services as well as for dependency injection". We are retrieving the $locale service. This is totally valid.