让我们设置一个简单的例子:
$scope.whatDoesTheFoxSay = function(){
$http.post("/backend/ancientMystery", {
...
如何全局转换发送帖子请求的网址?基本上我想在每个http请求前加一个URL。
我尝试过在应用程序启动时在包含url的$rootScope
中设置变量。但这不是我想要的代码:
$scope.whatDoesTheFoxSay = function(){
$http.post($rootScope.backendUrl + "/backend/hidingDeepInTheWoods", {
...
我是否正确假设我应该调查$httpProvider.defaults.transformRequest
?任何人都可以提供一些基本的示例代码吗?
答案 0 :(得分: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>
答案 1 :(得分:0)
进入AngularJS&#34;&#34;缓存破坏的问题并希望分享一个工作解决方案,其中还包括一个“取消缓存”的选项。 $templatecache
资源。
此解决方案正确返回值而不是承诺;)
,如果您的请求已包含$_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;
}
}
});
}]);
答案 2 :(得分: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 { }