我想知道是否有任何方法可以通过添加自定义信息来配置所有$ http请求标头。像config这样的东西:
splashscreen
但对于我将在不同服务中进行的所有$ http调用。我确定有一个解决方案:D。谢谢
答案 0 :(得分:21)
更简单的解决方案可能是使用Angular的run
块:
app.run(['$http', function ($http) {
$http.defaults.headers.common['Authorization'] = 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==';
$http.defaults.headers.common['Accept'] = 'application/json;odata=verbose';
}]);
注意:此解决方案允许您仅传递静态值一次,因为run
块仅执行一次。
答案 1 :(得分:0)
use the folllowing code and you can also control $http timeout from
config setting.
'use strict';
var app = angular.module('b2capp', []);
var apiRequestCount = 0;
app.config(function ($httpProvider) {
$httpProvider.interceptors.push(function ($rootScope, $q) {
return {
request: function (config) {
apiRequestCount++;
// config.timeout =300000;
return config;
},
response: function (response) {
return response;
},
responseError: function (rejection) {
switch (rejection.status) {
case 408:
console.log('connection timed out');
break;
}
// return $q.reject(rejection);
return rejection;
}
}
})
});
}]);
app.controller('myCtrl', function ($scope, $http, $timeout) {
var headers = {
//'Authorization': 'Basic ' + btoa(username + ":" + password),
'Access-Control-Allow-Origin': true,
'Content-Type': 'application/json; charset=utf-8',
"X-Requested-With": "XMLHttpRequest"
}
$http.post(url + 'Search_6e', reqCookie, {
headers
})
.then(function Success(response) {
$scope.myData = resultData;
console.log($scope.myData);
}, function myError(response) {
//error code
});