而且这个$inject的get()函数的工作方式不同.
来自配置或提供商的$injector,无法获取()任何服务! $injector.get(‘myService’)抛出错误:[$injector:unpr]未知提供者:myService,但$injector.has(‘myService’)返回true.这非常奇怪.
来自服务或控制器的$injector工作正常.
angular.module('app',[]) .provider('myProvider',function ($injector) { this.$get = ['$injector',function (serviceInjector) { return { providerInjector: $injector,serviceInjector: serviceInjector }; }]; }) .service('myService',function () {}) .controller('myCtrl',function ($scope,myProvider) { var providerInjector = myProvider.providerInjector; var serviceInjector = myProvider.serviceInjector; console.log(providerInjector === serviceInjector); // -> false console.log(serviceInjector.has('myService')); // `serviceInjector` has `myService` console.log(getMyService(serviceInjector)); // `serviceInjector` can get `myService` console.log(providerInjector.has('myService')); // `providerInjector` has `myService` too! console.log(getMyService(providerInjector)); // but `providerInjector` can't get `myService`! =( function getMyService(injector) { try { injector.get('myService'); return "OK"; } catch (e) { return e.toString(); } } });
谁能解释为什么有两种不同的注射器?
如何从provider / config使用$injector注入服务(当然,在服务初始化之后)?
附:我使用角1.3.13
解决方法
In the config function,$injector is the provider injector,where in the run function,$injector is the instance injector.
One’s the $injector at the config stage (only providers and constants accessible),and one’s the $injector at the run stage. The confusion may be that you’re thinking the $injector modifies itself to include the new stuff as it crosses the line from config to run,but that’s not true. They’re two separate (although related) objects,with their own caches of instances.
A more in-depth reason for this dichotomy will probably come from a deep learning of the $injector internals,but it seems like it’s been DRY-ed pretty hardcore,and the two types of injectors share almost all the same behavior,except in how they deal with “cache misses” in their instance caches.
We are going to overhaul the injector in v2,so this will get fixed there (getting rid of the config phase is one of the objectives of the injector v2).
看起来确实有两种不同的注入器,角度开发人员不会修复这种行为(在版本< 2.0中).由于某种原因,没有人在$injector文档中添加关于该方面的注释. 我无法找到一种方法如何在没有hacky技巧的情况下在配置块中真正获得实例注入器.所以,我写了一个可爱的提供者来解决这类问题.
.provider('instanceInjector',function () { var instanceInjector; function get() { return instanceInjector; } function exists() { return !!instanceInjector; } angular.extend(this,{ get: get,exists: exists }); this.$get = function ($injector) { instanceInjector = $injector; return { get: get,exists: exists }; } }) // We need to inject service somewhere. // Otherwise $get function will be never executed .run(['instanceInjector',function(instanceInjector){}])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。