I am studying my way around AngularJS at the moment. I pretty much dealt with how Angular handles dependency injection, but there is a space for which I cannot find an answer.
Let's say I have a service that retrieves data from the Internet based on a user request; it might look like this:
var webBasedServiceModule = angular.module('WebBasedService', []); webBasedServiceModule .factory('webBasedService', function ($http) { var rootUrl = "http://example.com/myApi?query="; return { getData: function(query) { return $http.get(rootUrl + query) .then(function(httpCallbackArg) { return doSomething(httpCallbackArg); }); } } });
I am introducing the $ http service, so I can make fun of it for testing. However, I have the root URL of my web service hardcoded in the class. Ideally, I would like to separate this URL from the service class and enter it as a dependency. However, I see no way to insert a string or other primitive into the Angular factory function. Ideally, I would like the code to look like this:
var webBasedServiceModule = angular.module('WebBasedService', []); webBasedServiceModule .factory('webBasedService', function ($http, rootUrl) { return { getData: function(query) { return $http.get(rootUrl + query) .then(function(httpCallbackArg) { return doSomething(httpCallbackArg); }); } } });
One solution that I see is to simply create an UrlProviderService and paste this service into the WebBasedService module, then call urlProvider.Url or similar. This seems a little smelly: it seems unnecessary to create a completely new service for only one piece of configuration data. I can even imagine that I can create a service that is a string, for example:
var urlServiceModule = angular.module('UrlService', []); urlServiceModule .factory('rootUrl', function () { return "http://example.com/myApi?query="; });
This is like abusing the concept of a service.
Does AngularJS provide a βstandardβ solution to the problem of entering primitives as configuration data? Or am I just using one of the solutions above?