AngularJs不能注入$在module.run提供和$喷油器服务 [英] AngularJs can't inject $provide and $injector services in module.run

查看:284
本文介绍了AngularJs不能注入$在module.run提供和$喷油器服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在angularjs动态定义服务,该文档称, $提供 $注射器 的服务,因此,他们应该在 module.run ..
我需要从应用程序引导的动态服务,这就是为什么我想要在 module.run

I'm trying to define services dynamically in angularjs, as the docs says, $provide and $injector are services, thus they should be injectable in module.run.. I need to make the dynamic services available from app bootstrap, that's why i'm trying to define them in module.run

angular.module('remote.interface',[])
.run(['$provide', '$injector', function(provide, injector){
  // provide dynamically
}]);

但在一个错误此结束: [$喷油器:unpr]未知提供商:$ provideProvider< - $提供,并同eror为 $注射器如果我尝试删除$提供注射。结果
哪里的错误?

but this ends up in an Error : [$injector:unpr] Unknown provider: $provideProvider <- $provide, and same eror for $injector if i try to remove $provide injection.
Where's the bug?

经过一番研究,我想是这样的:

after some research i tried something like this:

var module = angular.module('remote.interface',[])
.run([function(){
  var provide = module.provider(),
    injector = angular.injector();
    provide.value('my.val',{i:'am a value'});
    injector.get('my.val'); // this throws [$injector:unpr] Unknown provider: my.valProvider <- my.val
}]);

即使我删除 injector.get 通话,如果我尝试注入 my.val ,例如,在另一个模块的控制,角抛出同样的错误。

even if i remove the injector.get call, if i try to inject my.val, for example, in another-module's controller, angular throws the same error.

推荐答案

有一个看一下模块的文档,并有在该示例设置的意见,特别是这些意见一读。

Have a look at the documentation for module and have a read at the comments in the example setup, particularly these comments.

配置

您只能注入提供商(不是实例)到配置块

You can only inject Providers (not instances) into config blocks

运行

您只能注入情况下(不提供)到运行块

You can only inject instances (not Providers) into run blocks

这里是一个的jsfiddle设置为例注射提供$ $和喷油器正常。

Here is an example setup on JSFiddle injecting $provide and $injector correctly.

https://docs.angularjs.org/guide/module

angular.module('myModule', []).
  config(function(injectables) { // provider-injector
    // This is an example of config block.
    // You can have as many of these as you want.
    // You can only inject Providers (not instances)
    // into config blocks.
  }).
  run(function(injectables) { // instance-injector
    // This is an example of a run block.
    // You can have as many of these as you want.
    // You can only inject instances (not Providers)
    // into run blocks
  });

这篇关于AngularJs不能注入$在module.run提供和$喷油器服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆