Angular.js $ resource as a "service" with a dynamic root

I have a JS library that I would like to provide to my Angular based clients. He defines a number of services as follows:

angular.module('Services', [
    'ngResource'
]).factory('UserService', function($resource) {
    return function(whatsonUserId) {
        return $resource('/rest/user/:action');
    }
}. factory ...

To use my library, my clients just do:

app.controller('Ctrl', function(UserService) {
    ...
    UserService().doSomething()
}

When my clients use this library, they use it in their own HTML, which is explicitly loaded from their own URL, which makes the wrong URL for MY services. Thus, it is obvious that a way to fix this would be to present an absolute URL for $ resource:

        return $resource('www.my.server.url/rest/user/:action');

But I do not have only one 'my.server.url' - I have several. I have an intermediate environment, I have a development environment, and I have production environments - some of them per client.

: , "", " " ""?

+4
2

api. api, module.provider. , -

module.provider('serverConfig',function() {
    var serverUrl='val';     //default url
    this.setServerUrl=function(url) {
       serverUrl=url;
    };
    this.$get=[function(){
       return {url:serverUrl};
    }];
})

​​ , ,

factory('UserService', function($resource,serverConfig) {
    return function(whatsonUserId) {
        return $resource(serverConfig.url+'/rest/user/:action');
    }

myApp.config(["serverConfigProvider", function(serverConfigProvider) {
  serverConfigProvider.setServerUrl('serverUrlstring');
}]);
+4

. , AngularJS 1.4.3, :

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

, :

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

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

... .

+1

Source: https://habr.com/ru/post/1537488/


All Articles