Storing constants in services in AngularJS? -
very begginer question, sorry that!
i understand how store constants in services angularjs, example:
.value('baseurl', 'http://127.0.0.1:8001/api/v1/')
but how can create constant uses one? seems there no di in values ?!?
for example, if want create getusersurl
baseurl
string + 'users/' (concatenation)
i guess it's simple...but unable find how it. thank you.
you can store values in services, configure in run phase, , access values later. example:
.factory('urlservice', function() { var urlservice = {}; urlservice.baseurl = undefined; // can set default value urlservice.getusersurl = function() { if (urlservice.baseurl === undefined) { return undefined; } else { return urlservice.baseurl + '/users/'; } }; return urlservice; });
the run phase happens after config.
.run(function(urlservice) { urlservice.baseurl = 'localhost:8001/api/v1'; });
then, in controllers, etc. can inject urlservice , do
urlservice.getusersurl()
edit: rewrote answer.
edit 2: approach.
it appears me need baseurl
constant. so, do:
.value('baseurl', 'localhost:1337') .factory('urlservice', ['baseurl', function(baseurl) { return { getusersurl: function() { return baseurl + '/users/'; }, // or usersurl: baseurl + '/users/' // can primitive value } }]);
this approach works (and more "the angular way") if not need configure baseurl. example, if can fill in appropriate value of baseurl based on environment (dev, production, etc) running, wouldn't need configure it. or, if value constant.
Comments
Post a Comment