如何覆盖/更改值提供程序的 AngularJS 值

问题描述:

我想覆盖价值-

angular.module("data", []).value('apiBase', '/api1/data')

在运行时,我试图修改它-

at runtime, I tried to modify it with-

angular.module("data").value('apiBase', '/someotherapi/data')

在某些服务/控制器中,但它失败了,它没有覆盖 apiBase 的值.

in some service/controller, but it failed, it didn't override the value of apiBase.

我尝试在我的控制器中注入 apiBase 并更改它.

I tried to inject apiBase in my controller and change it.

angular.module('data').controller(function(apiBase){apiBase = '/someotherapi/data'})

失败了.

然后我尝试将 apiBase 定义更改为像

Then I tried change the apiBase defination to an object like

angular.module("data", []).value('apiBase', {"api_base_url":"/api1/data"})

然后在控制器中修改它:

then modifying it in controller:

angular.module('data').controller(function(apiBase){apiBase.api_base_url = '/someotherapi/data'})

它有效.所以我的问题是:为什么 angular.module('data').value('samekey', 'newvalue') 不能覆盖值?当它只是一个字符串/数字(主要类型.第二次尝试)时,为什么不能修改该值.在我看来 Value 提供程序是单例的,它应该改变.

It works. so my question is: why angular.module('data').value('samekey', 'newvalue') cannot override the value? why cannot modify the value when it is just a string/number (primary type. the second try). In my opinion Value provider is singleton, it should change.

请阅读有关 依赖关系的文档注入适用于AngularJS.

Please read the documentation on how the dependency injection works in AngularJS.

基本上,AngularJS 应用程序的创建分为两个阶段 - 配置阶段运行阶段.所有的配置代码,比如用特殊的 $provide 服务注册一个 .value(),都是在配置阶段完成的.一旦该阶段结束,就无法再进行配置,并且运行阶段开始,您的主模块被引导到 DOM,控制器和服务被实例化,等等.这允许依赖注入工作一种理智的、确定性的方式(通过其 ID 请求一个可注入对象总是为相同的 ID 返回相同的内容).

Basically, AngularJS application is created in two phases - configuration phase and run phase. All configuration code, like registering a .value() with the special $provide service, is done during configuration phase. Once that phase ends, no more configuration can be done and the run phase begins, where your main module is bootstrapped to the DOM, controllers and services are instantiated, etc. This allows the dependency injection to work in a sane, deterministic manner (requesting an injectable by its ID always returns the same thing for the same ID).