如何将默认端点添加到Angular $ http请求中?

时间:2015-07-30 10:42:05

标签: angularjs http gruntjs

我有一个Angular应用程序,它从环境文件中获取一些变量。我用Grunt更改了这个环境文件的内容。运行grunt任务后,我在environment.js中定义了一个变量var envBaseUrl = 'https://live.example.com';

我想根据env文件为http请求设置默认基本URL。

我之前使用过的一种方法是创建一个常量,然后手动将其添加到每个$ http URL中,例如:

var app = angular.module('myApp', []);
app.constant('BASE_URL', envBaseUrl || 'http://dev.example.com');
app.controller('myController', function ($scope, $http, BASE_URL) {
    $http.get(BASE_URL + '/someUrl').success(function(data, status, headers, config) { /* :) */ }).error(function(data, status, headers, config) { /* :( */ });
});

我的问题是我需要注入BASE_URL常量并手动添加到每个$http

我正在寻找类似下面的内容,但我没有成功:

app.config(function($httpProvider){
    $httpProvider.defaults.transformRequests.push(prependBaseUrl);
});

1 个答案:

答案 0 :(得分:1)

我按照Chandermani的建议使用了拦截器:

$httpProvider.interceptors.push(function(){
  return {
    request: function(config) {
      // prepend base url
      config.url = BASE_URL + config.url;
      return config;
    }
  };
});

但是,如果您在应用程序中使用插件,框架(例如:Angular UI路由器,JS数据,OAuth)提供程序和配置,这可能会非常棘手,因此要解决这个问题,我需要向拦截器添加更多逻辑,然后我问自己,在我需要的5个案例中,$http.get(BASE_URL + '/someUrl')是不是更容易?

如果我找到更好的解决方案,我会更新我的帖子。