angular.js $resource as a 'service' with dynamic root
angularjs, javascript, resources
Solution
This is a good use case for provider api. You can define your api using the `module.provider`. Define a provider for your server configuration, something like
module.provider('serverConfig',function() {
var serverUrl='val'; //default url
this.setServerUrl=function(url) {
serverUrl=url;
};
this.$get=[function(){
return {url:serverUrl};
}];
})
Once you define such a config service, use it in each of your own services like
factory('UserService', function($resource,serverConfig) {
return function(whatsonUserId) {
return $resource(serverConfig.url+'/rest/user/:action');
}
The provider needs to be configured at the config stage
myApp.config(["serverConfigProvider", function(serverConfigProvider) {
serverConfigProvider.setServerUrl('serverUrlstring');
}]);
Problem
I have a JS library that I would like to supply to my clients, that is based on Angular. It defines a number of services in the following way: ``` angular.module('Services', [ 'ngResource' ]).factory('UserService', function($resource) { return function(whatsonUserId) { return $resource('/rest/user/:action'); } }. factory ... ``` To use my library, my customers simply do: ``` app.controller('Ctrl', function(UserService) { ... UserService().doSomething() } ``` When my clients use this library, they use it in their own HTML which obviously loads from their own URL, making the root URL incorrect for MY services. So obviously the way to correct this would be to supply an absolute URL to $resource: ``` return $resource('www.my.server.url/rest/user/:action'); ``` But I don't have just one 'my.server.url' - I have a few. I have a staging environment, I have a development environment, and I have production environments - some are per customer. My question is: Is there a way I could have a generic 'service', and have the users of my library specify the 'server root' for 'Services' ?