如何覆盖/更改值提供者的AngularJS值 [英] How to override / change AngularJS value of value provider

查看:85
本文介绍了如何覆盖/更改值提供者的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()一样,都是在配置阶段完成的.该阶段结束后,将无法再进行任何配置,并且 run阶段开始,在该阶段中,您的主模块将引导至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).

这篇关于如何覆盖/更改值提供者的AngularJS值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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