$http & interceptor
how we can configure request and response data with interceptor during config time.
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.4/angular-filter.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.4/angular-filter.min.js"></script>
<div ng-app="myApp" ng-controller="DemoCtrl">
<div ng-repeat="user in users">{{user.name}} <strong>({{user.addP}})</strong> </div>
<input type="text" class="cssT" ng-model="idnumber" placeholder="type an id" ng-keyup="search($event,idnumber)" />
<div ng-show="ind">
<p>Name : <strong><span ng-bind="singleuser.name"></span> <span ng-bind="name"></span></strong></p>
<p>Status code : <strong><span ng-bind="statusC"></span></strong></p>
time taken <span ng-bind="timeTaken"></span>
</div>
</div>
CSS
.cssT {
color: red;
border-radius: 5px;
margin: 10px 0px 0px 10px;
padding-left: 5px;
}
JavaScript
var app = angular.module('myApp', []);
// define interceptor
app.factory('myHttpInterceptor', function($timeout,$q) {
return {
'request': function(config) {
console.log("m from request interceptor and below is the input config");
config.cache = false;
//changing config properties
config.headers['Cache-Control'] = 'no-cache';
config.headers['Authentication'] = 'authentication';
console.log(config);
//request config all done :)
config.requestTimestamp = new Date().getTime();
return config;
},
'requestError': function(rejectionRequest) {
console.log("from REQUEST ERROR")
return $q.reject("Couldnot have a successfull request, Sorry :(");
},
'response': function(response) {
console.log("m from RESPONSE interceptor");
if (response.config.url.indexOf('users') > -1) {
//response.data[0].name = 'Jake N (modified by interceptor)';
console.log(response);
angular.forEach(response.data, function(value, index) {
value.addP = value.id * 100;
})
//$timeout(function() {
//response.data[0].name = 'Jake N (modified by interceptor inside $timeout //function)';
// }, 3000)
}
response.config.responseTimestamp = new Date().getTime();
return response;
},
'responseError': function(rejectionRequest){
console.log("from RESPONSE ERROR")
//return $q.reject("Couldnot have a successfull response, Sorry :(");
rejectionRequest.errorMessage = "oh it works, 404 error";
return $q.reject(rejectionRequest)
}
}
});
app.config(function($httpProvider, $compileProvider) {
$httpProvider.interceptors.push('myHttpInterceptor');
//for GET, it doesnot work
//$httpProvider.defaults.headers.get['Cache-Control']= 'no-cache';
//for Common, it works
//$httpProvider.defaults.headers.common['Cache-Control']= 'no-cache';
...