加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS – 将工厂从另一个模块注入供应商

发布时间:2020-12-17 08:07:35 所属栏目:安全 来源:网络整理
导读:我有一个单独的模块的工厂,我想注入到我的模块的提供商,但我不断收到未知的提供商错误。我究竟做错了什么? 我想注射什么 var angularSocketIO = angular.module('socketioModule',[]);angularSocketIO.factory('socketio',[ '$rootScope','addr',function
我有一个单独的模块的工厂,我想注入到我的模块的提供商,但我不断收到未知的提供商错误。我究竟做错了什么?

我想注射什么

var angularSocketIO = angular.module('socketioModule',[]);
angularSocketIO.factory('socketio',[
    '$rootScope','addr',function($rootScope,addr) {
        var socket = io.connect(addr,{
            'sync disconnect on unload': true
        });
                ...
        return socket;
    }
]);

我试图注射的地方:

angular.module('myApp.services',['socketioModule'])
    .provider('greeter',['socketio',function(socket) {
        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);
        };
    }]);

结果

Error: [$injector:modulerr] Failed to instantiate module myApp due to:
[$injector:modulerr] Failed to instantiate module myApp.services due to: 
[$injector:unpr] Unknown provider: socketio
我认为是因为所有的提供商都在工厂之前实例化,因此提供商只能依赖于其他提供商。

作为一种方式,我正在使用angular.module的注射器方法来创建模块。
一个应该做你想要完成的东西:http://plnkr.co/edit/g1M7BIKJkjSx55gAnuD2

请注意,我也改变了工厂方法。工厂方法现在返回一个对象
使用连接方法。

var angularSocketIO = angular.module('socketioModule',['ng']);
angularSocketIO.factory('socketio',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"]);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读