如何更改AngularJS HTTP调用的基本URL? [英] How can I change the base URL of an AngularJS HTTP call?
问题描述
我的应用程序多次这样调用$ HTTP:
My application calls $HTTP many times like this:
this.$http({
method: this.method,
url: this.url
})
this.url始终设置为/app/getdata
The this.url is always set to something like /app/getdata
现在,我已将应用程序的后端移至另一台服务器,我将需要获取如下数据:
Now I have moved the back-end of my application to another server and I will need to get data like this:
https://newserver.com/app/getdata
有没有办法提供将用于所有$ http调用的基本URL?
Is there a way that I can supply a base URL that will be used for all the $http calls?
推荐答案
我倾向于将网址保持在需要的位置.因此,如果我有一项服务,那么我会将基本URL保留在那里.像这样:this.rootUrl = '/api/v1/';
I tend to keep my urls close to where they are needed. So if I have a service, then I'd keep the base url there; like this: this.rootUrl = '/api/v1/';
这使我可以使用其他上下文方法来扩展" URL.
This allows me to have additional contextual methods that 'extend' the url.
例如:
this.getBaseUrl = function(client_id, project_id) {
return this.rootUrl + 'clients/' + client_id + '/projects/' + project_id + '/';
};
然后我可以这样使用:
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 like this (within the same service):
this.closeActivity = function(activity_id, callback){
$http.get(this.rootUrl + 'close_activity/' + activity_id)
.success(callback)
.error(this.handlerError);
};
-harold
这篇关于如何更改AngularJS HTTP调用的基本URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!