I can't seem to find an answer to what seems like a reasonable question.
I am using the $http service to call web services for all of my app. All of the server API is hosted at a particular address. Is there any way in which I can get $http to always prefix the provided URL with the API server?
For example, if my API is at http://myAPi/API/
, I would like to be able to call:
$http.get("User")...
as opposed to:
$http.get("http://myAPI/API/User")
And Angular prefixes the request with the server address. The aim is to not have the URL spread throughout the app.
Is there a way to achieve this with Angular?
It's an old question but I made a solution some time ago
angular
.module('app')
.config(function ($httpProvider) {
$httpProvider.interceptors.push(apiInterceptor);
});
// api url prefix
var API_URL = 'http://localhost:8080/';
function apiInterceptor ($q) {
return {
request: function (config) {
var url = config.url;
// ignore template requests
if (url.substr(url.length - 5) == '.html') {
return config || $q.when(config);
}
config.url = API_URL + config.url;
return config || $q.when(config);
}
}
}
Since $http doesn't have a built-in way of handling this case (other than editing the angular.js source code), you can either wrap your $http in a service:
apiService.get('user'); //where the service defines the $http call and builds the URL
... or simply create an angular constant:
angular.module('myApp', []).constant('apiPrefix', 'http://myAPI/API/')
$http.get(apiPrefix + 'User')
Either way would result to "not have the URL spread throughout the app".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With