AngularJS глобально изменить URL-адрес каждого запроса в $http

Задайте простой пример:

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

Как я могу глобально преобразовать URL-адрес, куда отправляется почтовый запрос? По сути, я хочу добавить URL-адрес для каждого HTTP-запроса.

Я попытался установить переменную в $rootScope, содержащую URL-адрес при запуске приложения. Но это не то, что я хочу, чтобы мой код выглядел следующим образом:

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

Правильно ли я предполагаю, что я должен смотреть в $httpProvider.defaults.transformRequest? Может ли кто-нибудь предоставить мне некоторый базовый пример кода?

Ответы

Ответ 1

У меня есть другой подход использования перехватчика запросов с $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>

Ответ 2

Подходим к этой проблеме "перебора кеша в AngularJS" и хотели бы поделиться рабочим решением, которое также включает в себя возможность "un-cache" $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;
      }
    }
  });
}]);

Ответ 3

Современный подход заключается в реализации собственного 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 { }