I'm trying to define constants with other constants, but it seems that it can't be done, because the initial constant isn't ready when the required constant depending require it. I want to be sure if this isn't possible at all.
Currently I have constants in this way:
angular.module('mainApp.config', [])
.constant('RESOURCE_USERS_DOMAIN', 'http://127.0.0.1:8008')
.constant('RESOURCE_USERS_API', 'http://127.0.0.1:8008/users')
// Specific routes for API
.constant('API_BASIC_INFORMATION', RESOURCE_USERS_API + '/api/info')
.constant('API_SOCIAL_NETWORKS', RESOURCE_USERS_API + '/api/social')
;
The second two constants is what I want to accomplish
An easy way to do this is like this:
And use the constants like this:
Credits: link
The solution provided by @Linkmichiel is good, but if you desperately want to use one constant inside another, you can combine them in the config block:
After the config phase, all constants will be setup correctly (try out the snippet).
The moral of the story is: Angular is so cool that you can even change the constants.
As long as you don't need access to your constant in providers, this should work fine:
If you need access to you constants in providers, then I guess you have to do some more work:
Can't tell for sure if that's (im)possible. But a workaround would be to define the base constants as regular constants, and the higher-order ones as services using closures to make sure they cannot be altered.
Rough example:
And use it after injecting the service:
Not very elegant, but should get the job done.
The angular way to define dependencies between Controllers, Services and others is by dependency injection (DI). So if you have a controller A that depends on a service B you would have to create it like this.
See, angular will check the serviceB dependency and look for the service you created with that name. If you don't create one you will get an error.
So, if you want to create a constant A that depends on constant B, you would need to tell angular that A depends on B. But constant can't have a dependency. Constant can return a function, but the DI won't work for the constant. Check this Fiddle so you can see for which methods DI works.
So answering your question, you can't define a constant with other constants.
But you can do this:
Check this fiddle to see it working:
If you want to understand more about DI, check out this post.
I hope this can answer your question.
I do that this way: