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' ?

有帮助吗?

解决方案

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');
}]);

其他提示

Don't know about an earlier version. But as of AngularJS 1.4.3, the following seems to work:

.factory('UserService', function($resource) {
  // subdomain is defaulted to www
  return $resource("http://:subdomain.my.server.url/rest/user", {subdomain: 'www'});
})

Then the users can call it either with a new subdomain or not:

UserService.query({subdomain: 'user001'}).$promise.then(
// => http://user001.my.server.url/rest/user

or

UserService.query().$promise.then(
// => http://www.my.server.url/rest/user

It's static or dynamic... anyway you like it.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top