$provide 外部配置块 [英] $provide outside config blocks

查看:32
本文介绍了$provide 外部配置块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当然遗漏了一些关于注入器的基本观点,但我不明白为什么会这样

I'm certainly missing some fundamental point about the injector, but I fail to understand why exactly this

angular.module('app').config(function ($provide) {
    ...
});

还有这个

angular.module('app').config(function ($injector) {
    $injector.invoke(function ($provide) { ... });
});

按预期工作,而这

app.run(function($provide) {
    ...
});

会扔

错误:[$injector:unpr] 未知提供者:$provideProvider <- $provide

Error: [$injector:unpr] Unknown provider: $provideProvider <- $provide

从上面可以看出,config 与提供者有一些特殊的关系,而 run 处理实例,但我不确定是什么使 config 块很特别.

As follows from the above, config has some special relationship with providers, while run deals with instances, yet I'm unsure about the thing that makes config blocks so special.

因此,没有办法在 config 块之外访问 $provide,例如使用 angular.injector() (虽然它似乎也获得了提供者实例)?

As a consequence of that, is there no way to get to $provide outside config blocks, e.g. with angular.injector() (though it seems that it gets provider instances also)?

这个问题,除了单纯的好奇,还有一些实际的考虑.在 1.4 中,所有 $provide 函数都暴露给模块,但在 1.3 中并非如此.

The question, besides mere curiosity, also has some practical considerations. In 1.4 all of $provide functions are exposed to module, but that's not true for 1.3.

推荐答案

经过一些 Angular 注入器研究后,我能够对我自己的问题给出详尽的答案.

After some Angular injector study I was able to give an exhaustive answer to my own question.

本质上,$injector config 块和 provider 构造函数$injector 其他地方 是两个具有相同名称的不同服务,它们定义在内部提供者/实例缓存显式,连同 $provide(这个是在提供者缓存中定义的,因此它只能在 config 中注入).

Essentially, $injector in config blocks and provider constructor functions and $injector everywhere else are two different services with the same name, which are defined on internal provider/instance cache explicitly, together with $provide (this one is being defined in provider cache, hence it can be injected in config only).

虽然通常不推荐因为可能存在竞争条件,但可以将内部服务暴露给实例缓存并使特定于配置的 $provide$injector 可用于注入配置阶段结束后:

While generally not recommended because of probable race conditions, it is possible to expose internal services to instance cache and make config-specific $provide and $injector available for injection after config phase has ended:

app.config(function ($provide, $injector) {
  $provide.value('$providerInjector', $injector);
  $provide.value('$provide', $provide);
});

可能的应用程序正在随时配置服务提供者(如果可能)

The possible applications are configuring service providers any time (if possible)

app.run(function ($providerInjector) {
  var $compileProvider = $providerInjector.get('$compileProvider');
  ...
});

并在运行时定义新组件

app.run(function ($provide) {
  $provide.controller(...);
  ...
});

这篇关于$provide 外部配置块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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