How to override / change the value of Value Value Value in AngularJS

I want to override the value

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

at runtime, I tried changing it using

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

in some service / controller, but it did not pass, it did not override apiBase value.

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

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

it failed.

Then I tried changing defin apiBase to an object like

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

then changing it in the controller:

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

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

+5
source share
1 answer

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

Basically, an AngularJS application is created in two stages - the configuration phase and the launch phase. All configuration code, such as registering .value() with the special $provide service, is performed during the configuration phase. Once this phase ends, the configuration can no longer be completed and the start phase begins when your main module loads into the DOM, instances and services are created, etc. This allows dependency injection to work in a reasonable, deterministic way (requesting an injection by its identifier always returns the same for the same ID).

+7
source

Source: https://habr.com/ru/post/1207648/


All Articles