Detail http interception in AngularJS
- 2020-12-13 18:51:26
- OfStack
The http interception, or $http service, allows us to interact with the server, and sometimes we want to do something before sending the request and after receiving the response.
$httpProvider contains an array of interceptors.
Let's create an interceptor like this.
app.factory('myInterceptor', ['$log', function($log){
$log.debug('');
var myInterceptor = {};
return myInterceptor;
}])
Then sign up for interceptor.
app.config(['$httpProvider', function($httpProvider){
$httpProvider.interceptors.push('myInterceptor');
}])
Here are some examples of the $http intercept.
■ Asynchronous operations in interceptors
app.factory('myInterceotpr','someAsyncServcie', function($q, someAsyncServcie){
var requestInterceptor = {
request: function(config){
var deferred = %q.defer();
someAsyncService.doAsyncOperation().then(function(){
...
deferred.resolve(config);
}, function(){
...
deferred.resolve(config);
})
return deferred.promise;
}
};
return requestInterceptor;
})
Above, is a request interception that makes an asynchronous operation to update config based on the result of the asynchronous operation.
There are also response intercepts.
app.factory('myInterceptor',['$q', 'someAsyncService', function($q, someAsyncSercice){
var responseInterceptor = {
response: function(response){
var deferred = $q.defer();
someAsyncService.doAsyncOperation().then(function(response){
...
deferred.resolve(response);
}, function(response){
...
deferred.resolve(response);
})
return deferred.promise;
}
};
return responseInterceptor;
}])
■ Session intercept, request intercept
The server has two types of validation, one based on cookie and one based on token. For ES36en-based authentication, when the user logs in, one token is fetched from the server, which is sent to the server on every request.
Create an injector for session:
app.factory('sessionInjector',['SessionService', function(SessionService){
var sessionInjector = {
request: function(config){
if(!SessionService.isAnonymous){
config.headers['x-session-token'] = SessionService.token;
}
return config;
}
};
return sessionInjector;
}])
As you can see, the token returned from the server is placed in config.headers.
Registered injector:
app.config(['$httpProvider', function($httpProvider){
$httpProvider.interceptors.push('sessionInjector');
}])
Send 1 request:
$http.get('');
Before interception:
{
"transformRequest":[null],
"transformResponse":[null],
"method":"GET",
"url":"",
"headers":{
"Accept": "application/json, text/plain,*/*"
}
}
After interception, one more x-ES65en-ES66en field is added to headers:
{
"transformRequest":[null],
"transformResponse":[null],
"method":"GET",
"url":"",
"headers":{
"Accept": "application/json, text/plain,*/*",
"x-session-token":......
}
}
■ Timestamp, request and response interception
app.factory('timestampMarker',[function(){
var timestampMarker = {
request:function(config){
config.requestTimestamp = new Date().getTime();
return config;
},
response: function(response){
response.config.responseTimestamp = new Date().getTime();
return config;
}
};
return timestampMarker;
}])
Above, intercept on request and response, assign the current time on config.requestTimestamp and ES76en.responseTimestamp.
Register interceptors:
app.config(['$httpProvider', function($httpProvider){
$httpProvider.interceptors.push('myInterceptor');
}])
0
Then, at the time of application, you can calculate the time it takes to respond to the request.
app.config(['$httpProvider', function($httpProvider){
$httpProvider.interceptors.push('myInterceptor');
}])
1
■ Request error recovery, request interception
Simulate the error case of 1 request interception:
app.config(['$httpProvider', function($httpProvider){
$httpProvider.interceptors.push('myInterceptor');
}])
2
Intercept request error:
app.factory('requestRecoverer',['$q', function($q){
var requestRecoverer = {
requestError: function(rejectReason){
if(rejectReason === 'requestRejector'){
// Restore requests
return {
transformRequest:[],
transformResponse:[],
method:'GET',
url:'',
headers:{
Accept:'application/json, text/plain, */*'
}
};
} else {
return $q.reject(rejectReason);
}
}
};
return requestRecoverer;
}])
Register interceptors:
app.config(['$httpProvider', function($httpProvider){
$httpProvider.interceptors.push('myInterceptor');
}])
4
■ Session error recovery, response intercept
app.config(['$httpProvider', function($httpProvider){
$httpProvider.interceptors.push('myInterceptor');
}])
5
Above is the entire content of this article, I hope to help you with your study.