How to change the base URL of an AngularJS HTTP call?

My application calls $ HTTP many times:

this.$http({ method: this.method, url: this.url }) 

This .url always has something like / app / getdata installed p>

Now I have moved the back-end of my application to another server, and I will need to get such data:

 https://newserver.com/app/getdata 

Is there a way I can provide a base url that will be used for all $ http calls?

+8
angularjs
source share
4 answers

I try to keep my URLs close to where they are needed. Therefore, if I have a service, I would keep the base url; for example: this.rootUrl = '/api/v1/';

This allows me to have additional contextual methods that โ€œextendโ€ the URL.

For example:

 this.getBaseUrl = function(client_id, project_id) { return this.rootUrl + 'clients/' + client_id + '/projects/' + project_id + '/'; }; 

What can I use as follows:

 this.createActivity = function(client_id, project_id, activity_name, callback) { $http.post(this.getBaseUrl(client_id, project_id) + 'activities', {activity: {name: activity_name}}) .success(callback) .error(this.handlerError); }; 

or how it is (within the same service):

 this.closeActivity = function(activity_id, callback){ $http.get(this.rootUrl + 'close_activity/' + activity_id) .success(callback) .error(this.handlerError); }; 

-harold

+1
source

I found an alternative solution instead of the <base> : written in coffeescript

 $httpProvider.interceptors.push ($q)-> 'request': (config)-> if config.url.indexOf('/api') is 0 config.url = BASE_URL+config.url config 
+16
source

I usually save the settings in angular constants and inject them into services.

+7
source

set baseUrl to $rootScope :

 app.run(function($rootScope) { $rootScope.baseUrl = "https://newserver.com"; }); 

add $rootScope to your application controllers:

 app.controller('Controller', ['$rootScope', function($rootScope){ ... this.$http({ method: this.method, url: $rootScope.baseUrl + this.url }) 
-one
source

All Articles