微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

AngularJS全局修改$http中每个请求的URL

我们来设一个简单的例子:
$scope.whatDoesTheFoxSay = function(){
    $http.post("/backend/ancientMystery",{
...

如何将发送请求发送到的URL全局变换为?本质上,我想为每个http请求添加一个URL.

我试过的是在应用程序启动时在$rootScope中设置一个包含url的变量.但这不是我想要的代码如下:

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

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

我有另一种使用请求拦截器与$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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐