How to inject dependencies into a provider using Angularjs?

前端 未结 5 1727
谎友^
谎友^ 2020-12-29 03:00

Is it possible to do DI in a provider method?

In this example

angular.module(\'greet\',[])
.provider(\'greeter\',function() {

  this.$get=function()         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-29 03:12

    You can inject constants and other providers into a provider. Not services or factories - with one exception. It seems that you can inject the $injector service into a provider - at least, you can in AngularJS 1.3.16.

    .provider('foo', ['$injector', function ($injector) {
      var messagePrefix = $injector.get('msgPrefix');
      this.message = '';
    
      this.$get = function() {
        var that = this;
        return function() {
          return messagePrefix + that.message;
        }
      };
    }])
    

    You can use the injector outside the $get method, but you still can't get services from it at configure time.

    See here for a demo.

提交回复
热议问题