How to add service to angular constant

I would like to define a constant using the service $locale

. Constants are objects, so I cannot inject them as a parameter as in the case of a controller. How can I use it?

angular.module('app').constant('SOME_CONSTANT', {
  'LOCALE': $locale.id.slice(0, 2)
})

      

+3


source to share


2 answers


You can manually grab $locale

with $ injector . Observe the following ...

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

      



JSFiddle example

+2


source


this is not possible for two reasons.

  • constant cannot have dependencies (see table below https://docs.angularjs.org/guide/providers )

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



Alternatively, you can create a factory service type that can have dependencies and can create an object or primitive

angular.module('app')
  .factory('LOCALE_ID', function($locale) {
      return {'LOCALE': $locale.id.slice(0, 2)}
  })

      

+5


source







All Articles