2013-06-18 64 views
7

我似乎無法找到似乎是一個合理問題的答案。

我正在使用$ http服務爲我的所有應用程序調用Web服務。所有的服務器API都託管在一個特定的地址。有什麼方法可以讓我獲得$ http始終在API服務器前面提供的URL?

例如,如果我的API是http://myAPi/API/,我想能夠調用:

$http.get("User")... 

,而不是:

$http.get("http://myAPI/API/User") 

和角度前綴與服務器地址的請求。目的是不讓URL遍佈整個應用程序。

有沒有辦法用Angular實現這一點?

+0

可能重複在AngularJS](http://stackoverflow.com/questions/17011616/using-a-relative-path-for-a-service-call-in-angularjs) – Stewie

+0

可能重複的細節我目前有 - 本質上是服務器的位置存儲在某種變量中,並手動添加到每個調用的前綴中。如果可以的話,我正在尋找一種前綴自動添加前綴的方法。 – jwest

回答

4

因爲$ HTTP不具備處理這種情況下(不是編輯的angular.js源代碼等),內置的方式,你可以換你的$ HTTP的服務:

apiService.get('user'); //where the service defines the $http call and builds the URL 

...或者乾脆創建一個角度不變:

angular.module('myApp', []).constant('apiPrefix', 'http://myAPI/API/') 

$http.get(apiPrefix + 'User') 

無論哪種方式會導致「不具備整個應用程序的URL蔓延」。

-1

可以向http提供程序添加攔截器。

// register the interceptor as a service 
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { 
    return { 
    // optional method 
    'request': function(config) { 
     // do something on success 
     return config || $q.when(config); 
    } 
} 

然後你註冊你的攔截器。

$httpProvider.interceptors.push('myHttpInterceptor'); 

你只需要編輯配置:)

+4

要小心,模板也會被攔截。你不想加載'/ api/my_template.html' – Utopik

4

這是一個老問題,但我前一段時間做了一個解決方案

angular 
    .module('app') 
    .config(function ($httpProvider) { 
    $httpProvider.interceptors.push(apiInterceptor); 
    }); 

// api url prefix 
var API_URL = 'http://localhost:8080/'; 

function apiInterceptor ($q) { 
    return { 
    request: function (config) { 
     var url = config.url; 

     // ignore template requests 
     if (url.substr(url.length - 5) == '.html') { 
     return config || $q.when(config); 
     } 

     config.url = API_URL + config.url; 
     return config || $q.when(config); 
    } 
    } 
} 
的[使用相對路徑爲服務調用