2013-09-24 68 views
15

每个请求的URL让我们建立一个简单的例子:

$scope.whatDoesTheFoxSay = function(){ 
    $http.post("/backend/ancientMystery", { 
... 

我怎样才能在全球范围变换在POST请求被发送到URL?基本上我想为每个http请求添加一个URL。

我试过的是在应用程序启动时在包含url的$rootScope中设置一个变量。但是,这不是我想要我的代码看起来像:

$scope.whatDoesTheFoxSay = function(){ 
    $http.post($rootScope.backendUrl + "/backend/hidingDeepInTheWoods", { 
... 

我是正确假设我应该看看$httpProvider.defaults.transformRequest?任何人都可以提供一些基本的示例代码吗?

回答

37

我使用请求拦截器与$ HTTP的另一种方法,将处理所有的URL在一个共同的地方

<!doctype html> 
<html ng-app="test"> 
    <head> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.js"></script> 

    </head> 
<body ng-controller="test" >  


<!-- tabs --> 


<script> 
    var app = angular.module('test', []); 
    app.config(function ($httpProvider) { 
     $httpProvider.interceptors.push(function ($q) { 
      return { 
       'request': function (config) { 
        config.url = config.url + '?id=123'; 
        return config || $q.when(config); 

       } 

      } 
     }); 
    }); 

    app.controller('test', function ($scope,$http) { 
     $http.get('Response.txt').success(function (data) { alert(data) }).error(function (fail) { 

     }); 
    }); 

    </script> 
</body> 


</html> 
+0

当使用这种沿'ngToast'我得到的错误'错误:[$编译:tplrt]模板指令 '干杯' 必须有一个根element' –

+2

'''config.url =配置。 url +'?id = 123';返回配置|| $ q.when(config);'''在访问'''config.url''后,什么会使'''config'''计算为false? –

0

陶然成的“缓存清除在AngularJS”这个问题,并希望分享工作该解决方案还包括一个用于“缓存”$templatecache资源的选项。

此解决方案正确返回一个值而不是承诺;),如果您的请求已包含$_GET值,则不会形成格式不正确的URL。

var __version_number = 6.0; // Date.now('U'); // 'U' -> linux/unix epoch date int 

app.config(['$httpProvider', function($httpProvider) { 
    $httpProvider.interceptors.push(function() { 
    return { 
     'request': function (config) { 
     // !!config.cached represents if the request is resolved using 
     //  the angular-templatecache 
     if (!config.cached) { 
      config.url += ((config.url.indexOf('?') > -1) ? '&' : '?') 
      + config.paramSerializer({v: __version_number}); 
     } else if (config.url.indexOf('no-cache') > -1) { 
      // if the cached URL contains 'no-cache' then remove it from the cache 
      config.cache.remove(config.url); 
      config.cached = false; // unknown consequences 
      // Warning: if you remove the value form the cache, and the asset is not 
      //   accessable at the given URL, you will get a 404 error. 
     } 
     return config; 
     } 
    } 
    }); 
}]);