如何更改AngularJS HTTP调用的基本URL?

如何更改AngularJS HTTP调用的基本URL?,angularjs,Angularjs,我的应用程序多次调用$HTTP,如下所示: this.$http({ method: this.method, url: this.url }) https://newserver.com/app/getdata this.createActivity = function(client_id, project_id, activity_name, callback) { $http.post(this.getBaseUrl(clien

我的应用程序多次调用$HTTP,如下所示:

    this.$http({
        method: this.method,
        url: this.url
    })
https://newserver.com/app/getdata
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);
};
this.url始终设置为类似/app/getdata的值

现在,我已将应用程序的后端移动到另一台服务器,我需要获得如下数据:

    this.$http({
        method: this.method,
        url: this.url
    })
https://newserver.com/app/getdata
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);
};

是否有一种方法可以提供用于所有$http调用的基本URL?

我通常将设置保留在角度常量中,并将其注入服务。

$rootScope
中设置基本URL:

app.run(function($rootScope) {
    $rootScope.baseUrl = "https://newserver.com";
});
$rootScope
添加到应用程序的控制器中:

app.controller('Controller', ['$rootScope', function($rootScope){
    ...

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

我倾向于将我的URL放在需要它们的地方。因此,如果我有一个服务,那么我会将基本url保留在那里;像这样:
this.rootUrl='/api/v1/'

这允许我使用其他上下文方法来“扩展”url

例如:

this.getBaseUrl = function(client_id, project_id) {
    return this.rootUrl + 'clients/' + client_id + '/projects/' + project_id + '/';
};
我可以这样使用:

    this.$http({
        method: this.method,
        url: this.url
    })
https://newserver.com/app/getdata
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);
};
或类似于此(在同一服务中):


-harold

我找到了替代方案,而不是
标签: 用咖啡脚本写的

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

在app.js中的某个位置设置baseUrl,并在需要时使用
baseUrl+this.url
。类似于
var baseUrl=“newserver.com/”。如果您的后端与angular应用程序位于不同的服务器上,则您可能还具有“使用访问控制允许原点”标题。请看,您可能会看到Restanglar-在那里,您可以使用一种方法更改基本url。这是非常糟糕的设计。它将共享配置附加到一个对象,该对象暴露了数百个不相关的关注点。至少使用
app.value('baseUrl','https://newserver.com');并注入。这种方法对我更有吸引力。我更喜欢截取,而不是向我的服务中注入大量常量。有人能告诉我一些文档来了解我如何使用它吗?