Search code examples
apiurlangularjsservicerestangular

Restangular setBaseUrl in the run messed up?


I have three service in my angular service module, and I put

Restangular.setBaseUrl(api_url);

in each of my service with different api_url, and I expect to use different service with different url;

but when I post to one of the service say api_url = a/v1/c/, what I get is post to api_url = b/v1/c;

I think the problem is the setBaseUrl part, for example:

factory.Aservice = function(Restangular){
    Restangular.setBaseUrl('/a/v1');

    var alist= Restangular.all('c/');

    return {
        createA:function(){
            alist.post(data)
        }
    }
}

 factory.Bservice = function(Restangular){
    Restangular.setBaseUrl('/b/v1');

    var blist= Restangular.all('d/');

    return {
        createB:function(){
            blist.post(data)
        }
    }
}

when I call Aservice.createA(),the post url is '/b/v1/c',which is wrong.

any idea why?


Solution

  • You don't seem to understand scoping of a serivce. Angular instantiates services in a lazily-loaded manner. Since both your services operate on the same Restangular, it is normal that whichever service loaded last, would be the one that will override the restangular configuration last:

    http://plnkr.co/edit/o974TqeunG9DGQONRNDT?p=preview

    I created a Plunkr which illustrates that.

    Also created a Plunkr which shows the correct way to do that.

    http://plnkr.co/edit/XYEQpLZaRAjxNUImCJMP?p=preview