我有一个单独模块的工厂,我想将其注入模块的提供程序中,但是却不断收到未知的提供程序错误。我究竟做错了什么?
我想注入的是:
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
我认为是因为所有提供程序都在工厂之前实例化,因此提供程序仅需依赖其他提供程序。
作为一种解决方法,我正在使用创建模块的injector方法angular.module。一个可以完成您想完成的任务的插件:http ://plnkr.co/edit/g1M7BIKJkjSx55gAnuD2
injector
angular.module
注意,我也更改了工厂方法。现在,factory方法将使用connect方法返回对象。
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"]);