0

I have multiple services providing access to api controllers such as:

app.service('adminSvc', function($resource) {
    return {
        getTextSample: function() {
            return $resource('/admin/TextGenerator/GetTextSample').get();
        }    
    }
});

Is there better way than providing server in variable?

app.service('adminSvc', function($resource) {
    return {
        getTextSample: function(server) {
            return $resource(server + '/admin/TextGenerator/GetTextSample').get();
        }    
    }
});
cpoDesign
  • 8,953
  • 13
  • 62
  • 106
  • 1
    Does this question give you any help? http://stackoverflow.com/questions/22707699/how-to-create-this-global-constant-to-be-shared-among-controllers-in-angularjs/22708212#22708212 – Lee Willis Jun 30 '14 at 11:47

2 Answers2

0

you can create configuration server that holds all your base URIs and credentials that can be injected where needed, or could have a communications server that handles all requests, and takes the relative, path, method and parameters as arguments and issues the requests and returns a promise to be handled on the other services. both methods allow you to abstract layers the second allows you to decouple your communication and provides more flexibility if you decide to switch providers since your services will only handle promises and no actual communications, they would be able to work with network responses, memory data, or files data

Dayan Moreno Leon
  • 5,357
  • 2
  • 22
  • 24
0

I have recently faced such problem, I solved this by listing all my urls and used $interpolate service to resolve all urls by using a certain base url.

Something like this, creating a Utils service with a method stringResolver() that interpolates each property value and assigning it to the REST services URLS property.

  .factory('Utils', function($interpolate) {
    return {
      stringResolver: stringResolver
    };

    function stringResolver(objectStrings) {
      var string, index;
      for(index in objectStrings)
        objectStrings[index] = $interpolate(objectStrings[index])(objectStrings);
      return objectStrings;
    }
  })

  .factory('REST', function(Utils) {
      var REST = {},
      URLS = REST.URLS = Utils.stringResolver({
        BASE: 'http://my-base-url.com',
        AUTHORIZATION: '{{BASE}}/oauth/access_token',
        REFRESH_AUTHENTICATION: '{{BASE}}/refresh',
        LOGIN: '{{BASE}}/login',
        REGISTER: '{{BASE}}/register',
        USER: '{{BASE}}/user',
        USERS: '{{BASE}}/users/:user_id',
        MODULES: '{{BASE}}/modules/:module_id',
        READINGS: '{{MODULES}}/readings/:reading_id',
        QUESTIONS: '{{READINGS}}/exam/questions/:question_id',
        CHOICES: '{{QUESTIONS}}/choices/:choice_id'
      });

      REST.LOGIN = $resource(REST.URLS.LOGIN);
      REST.REGISTER = $resource(REST.URLS.REGISTER);

      return REST;
  });
ryeballar
  • 29,658
  • 10
  • 65
  • 74