最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to inject service to angular constant - Stack Overflow

programmeradmin6浏览0评论

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)
})

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)
})
Share Improve this question edited Jul 15, 2015 at 15:21 scniro 17k8 gold badges66 silver badges107 bronze badges asked Jul 15, 2015 at 13:59 ciemborciembor 7,33714 gold badges61 silver badges103 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

this is not possible for two reasons.

  1. constant can not have dependencies (see table bottom https://docs.angularjs/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)}
  })

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

发布评论

评论列表(0)

  1. 暂无评论