21

让我们建立一个简单的例子:

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

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

我尝试的是$rootScope在应用程序启动时在包含 url 的变量中设置一个变量。但这不是我希望我的代码看起来的样子:

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

假设我应该调查一下,我是否正确$httpProvider.defaults.transformRequest?谁能给我一些基本的示例代码?

4

3 回答 3

42

我有另一种使用带有 $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>
于 2013-09-24T14:48:08.010 回答
0

遇到“AngularJS 中的缓存破坏”这个问题,并希望分享一个可行的解决方案,其中还包括“取消缓存”$templatecache资源的选项。

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

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;
      }
    }
  });
}]);
于 2016-12-02T22:43:57.057 回答
0

现代方法是实现自定义Http客户端。

export function getCustomHttp(xhrBackend: XHRBackend, requestOptions: RequestOptions) {
    return new CustomHttp(xhrBackend, requestOptions);
}

export class CustomHttp extends Http {
    public constructor(backend: XHRBackend, private defaultOptions: RequestOptions) {
        super(backend, defaultOptions);
    }

    public request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
        url = 'https://www.customURL.com/' + url; // Of course, you'd pull this from a config
        return super.request(url, options);
    }
}

然后你只需修改你app.module的如下:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    AppRoute,
    RouterModule
  ],
  providers: [
    HttpModule,
    {
      provide: Http,
      useFactory: getCustomHttp,
      deps: [XHRBackend, RequestOptions]
    }
  ],
  bootstrap: [AppComponent]
})

export class AppModule { }
于 2019-04-09T12:36:08.573 回答