我似乎无法找到一个似乎是一个合理问题的答案.
我使用$ http服务为我的所有应用程序调用Web服务.所有服务器API都托管在特定地址.有没有什么方法可以让$ http总是在提供的URL前面加上API服务器的前缀?
例如,如果我的API处于http://myAPi/API/
,我希望能够调用:
$http.get("User")...
Run Code Online (Sandbox Code Playgroud)
而不是:
$http.get("http://myAPI/API/User")
Run Code Online (Sandbox Code Playgroud)
Angular将请求作为服务器地址的前缀.目的是不在整个应用程序中传播URL.
有没有办法用Angular实现这个目标?
这是一个老问题,但我不久前提出了一个解决方案
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
由于$ http没有处理这种情况的内置方法(除了编辑angular.js源代码),您可以将$ http包装在服务中:
apiService.get('user'); //where the service defines the $http call and builds the URL
Run Code Online (Sandbox Code Playgroud)
...或简单地创建一个角度常数:
angular.module('myApp', []).constant('apiPrefix', 'http://myAPI/API/')
$http.get(apiPrefix + 'User')
Run Code Online (Sandbox Code Playgroud)
两种方法都将导致“ URL不在整个应用程序中传播”。
归档时间: |
|
查看次数: |
7240 次 |
最近记录: |