AngularJS - Injecting factory from another module into a provider

前端 未结 2 626
我在风中等你
我在风中等你 2020-12-02 19:24

I have a factory from a separate module that I would like to inject into a provider for my module, but I keep getting unknown provider errors. What am I doing wrong?

相关标签:
2条回答
  • 2020-12-02 19:53

    I think you can add dependencies via $get method in provider:

    angular.module('myApp.services', ['socketioModule'])
      .provider('greeter', [
        function() {
            ...
            this.$get = ['socketio', function(socket, version) {
                function Greeter(a) {
                      this.salutation = salutation;
                      socket._emit('hello')
    
                      this.greet = function() {
                          return salutation + ' ' + a;
                      }
                 }
                 return new Greeter(version);
          }];
       }  
    ]);
    
    0 讨论(0)
  • 2020-12-02 19:54

    I think is because all the providers are instantiated before the factories and so a provider has to depend only on other providers.

    As a way around that, I am using the injector method of angular.module to create the module. A plunker that should do what you were trying to accomplish: http://plnkr.co/edit/g1M7BIKJkjSx55gAnuD2

    Notice that I changed also the factory method. The factory method is now returning an object with a connect method.

    var angularSocketIO = angular.module('socketioModule', ['ng']);
    angularSocketIO.factory('socketio', [
        '$rootScope',
        function($rootScope) {
          return {
            connect: function(addr) {
              var socket = io.connect(addr, {
                'sync disconnect on unload': true
              });
    
              return socket;
            }
          };
        }]);
    
    
      angular.module('myApp.services', ['socketioModule'])
      .provider('greeter', [
        function() {
          var injector = angular.injector(['socketioModule']);
          var socketio = injector.get('socketio');
    
          var salutation = 'Hello';
          this.setSalutation = function(s) {
            salutation = s;
          }
    
          function Greeter(a) {
            this.salutation = salutation;
            socket._emit('hello');
    
            this.greet = function() {
              return salutation + ' ' + a;
            };
          }
    
          this.$get = function(version) {
            return new Greeter(version);
          };
        }
      ]);
    
    
      var myApp = angular.module('myApp', ["myApp.services"]);
    
    0 讨论(0)
提交回复
热议问题