尽pipe存在服务,但不注入依赖项

所以我一直在做Angular.js项目一段时间,现在将在竞争中使用,并在一半的时间,我意识到我需要一个插件系统dynamic加载一些必要的代码在运行时。 到目前为止,我发现angular.js并不是很适合在运行时加载服务。 由于代码只能在比赛时间提供给竞争对手,我只能提供一个不成功的例子。

// ex1.coffee mainModule = angular.module('mainModule') mainModule.service('needed', () -> @neededFunc() -> console.log "just an example" return this mainModule.service('ex1', ($injector) -> @loadFile = (u, pluginName) -> $.ajax dataType: "script", url: u, data: null, success: (jqxhr, textStatus) => $injector.invoke([pluginName, (plugin) => plugin.testFunc() error: (jqxhr, textStatus, errorThrown) -> console.log "couldn't find the script" return this // ex2.coffee mainModule = angular.module('mainModule') mainModule.service('ex2', (needed) -> @testFunc = () -> needed.neededFunc() console.log "in this dynamically loaded file" return this 

隐含的东西:有一个名为mainModule的现有模块。 jquery和angular已经被包含在dom中。 ex1.js已经包含在dom中,而ex2.js尚未包含在dom中。 u是文件ex2.js和pluginName =“ex2”的url。 当成功处理程序被调用时,invoke函数失败,说ex2Provider不存在。 但是,如果我在成功callback中断点并检查mainModule._invokeQueue,那么确实存在一个服务名为“ex2”的数组,因此在模块中肯定有一个现有的配方,但$ injector.invoke调用仍然失败。 如果我修改成功处理程序来调用,$ injector.has pluginName,则失败。 有人能告诉我这个模块如何能够知道这个dynamic加载服务的提供者,但不能注入$注入函数调用吗? 该项目是一个咕噜咕噜的项目。

还在学习angular度,所以如果有一些概念,我错过了或说错了,请告诉我。

AngularJS在加载时会引导一个模块。 在引导期间,所有依赖关系都由注入器初始化。

 angular.module('mainModule').service('ex2', .....); 

当你通过AJAX执行上述操作时,会 mainModule已经被引导之后发生。 service()会使引导程序排队,但bootstrapping不会再发生。

这是从引导angular度的手册。

加载或定义模块后,应该调用angular.bootstrap()。 应用程序引导后,不能添加控制器,服务,指令等。

我想你可以做的是创build一个新的模块,并将其附加到现有的模块。

所以你的AJAX代码可能看起来像这样。

 angular.module('ex2Module',[]).service('ex2', .....); angular.module('mainModule').requires.push('ex2Module'); $rootScope.$digest(); 

我不能testing这个,但我认为这会导致新的模块ex2Module被引导,并作为依赖添加到现有的mainModule 。 注入器应该看到这个模块排队引导并安装它。

希望这可以帮助。