Objective
In the angular framework, the creation team encapsulates the AJAX request for the consumer and exposes the associated interface through the $http service. Angular in its official document, $http the bottom of the service is responding to common web security attacks, which means that using AJAX encapsulated in $http Services provides users with a more secure security. As a framework to ensure the usability of the framework, the suitability is necessary. Angular in the design, implementation also reflects the good style. When we use Ajax, sometimes we want to be able to do some processing before the request is initiated or after the request is received, for example: Before the request is launched, Adds a message segment to the request header. Manage a request processing state when the request returns, such as a unified handling of 404 states, and so on. Angular's $http service is fully considered in the design implementation. Next, let's learn and learn how to add interceptors to the $http service and how to implement similar interceptor mechanisms in our own implementation services.
What is Interceptor –what are interceptors?
Interceptor (interceptors) are a relatively common mechanism in the server-side framework, such as the spring,struts2 in Java frameworks such as the basic configuration items. Interceptors provide a mechanism that allows developers to define an action (action) Code that executes before and after execution, which can be code that blocks execution of an action before it is executed, or code that modifies some behavior of the target action. (In AOP (aspect-oriented programming) interceptors are used to intercept a method or field before it is accessed, and then add some action before or after it. More common in the spring framework)
Interceptors in the $http service
View APIs or source code we can see that the implementation of angular provides an array named interceptors through Httpprovider. This array accepts the Interceptor service registration, The registration of the process will eventually form the interceptor chain. This way, each time the HTTP service is invoked, the angular will modify the corresponding Ajax action through our defined intercept point (slice). The theory is not much said, the following start into combat:
How to declare an interceptor in angular
Interceptor declaration
module.factory (' Httpinterceptor ', [' $log ', function ($log) {
$log. Debug (' $log is Here to show you the This is a regular factory with injection ');
return {
//do something
};
}]);
How to register a declared interceptor in the $http service
Add the Interceptor to $httpProvider. Interceptors
module.config ([' $httpProvider ', function ($httpProvider) {
$httpProvider. Interceptors.push (' Httpinterceptor ');
}];
Through the above simple two steps, we basically completed the HTTP service interceptor to write and Add. But the above code fragment is not actually used, in order to really implement the interception operation, we also need to follow the HTTP service exposed to the point of interception can be related to code writing.
$httpProvider expose the points that can be intercepted?
- The Request:request method can implement interception requests: This method executes before HTTP sends the request to the server, so we can modify the configuration or do other things in the view of the method. The method receives the request configuration object (Requestconfigurationobject) as an argument and must then return the configuration object or promise. If an invalid configuration object is returned or promise is rejected, the HTTP call fails.
- The Response:response method can intercept the response: This method executes after HTTP receives a response from the server, so we can modify the response message or do other things. The method receives the Response object (Responseobject) as an argument, and then must return the response object or promise. The response object includes the request configuration (requestconfiguration), header (headers), State (status), and data from the background. If an invalid response object is returned or the promise is rejected, the HTTP call fails.
- The Requesterror:requesterror method can implement a blocking request exception: Sometimes a request fails or is rejected by the interceptor. Requesting an exception interceptor captures requests that have been interrupted by the last request interceptor. It can be used to recover requests or sometimes to undo the configuration that was made prior to the request, such as closing the progress bar, activating the button and the input box, and so on.
- The Responseerror:responseerror method can implement blocking response exceptions: Sometimes our backend calls fail. It is also possible that it was rejected by a request interceptor or interrupted by the last response interceptor. In this case, the response exception interceptor can help us recover the background call.
The use of the exposed interface is also exceptionally simple, and we can declare a $http service interceptor as a simple service, and leave it to the angular injection mechanism to use our configured interceptor.
Declares an interceptor
module.factory (' Sessioninjector ', [' Authservice ', function (Authservice), like declaring a angular service) {
return {
request:function (config) {
if (!authservice.isanonymus) {
config.headers[' x-session-token '] = Authservice.token;
}
return config;}}
];
We then add our declared interceptors to the $httpprovider interceptor chain, and the subsequent service injection angular will be responsible for perfecting
module.config ([' $httpProvider ', function ($ Httpprovider) {
$httpProvider. Interceptors.push (' Sessioninjector ');
}]);
Asynchronous support for $http service interceptor
In some scenarios, we want to be able to perform some asynchronous operations in the interceptor. Then, according to the different processing results of different interception operations, Angularjs in the design of the time also very good support for this feature. ANGULARJS allows us to intercept the method, We can return a promise object. As in the HTTP service, if we return a Promise object, the HTTP service will delay initiating the network request or delaying the response request result.
Module.factory (' Myinterceptor ', [' $q ', ' Someasyncservice ', function ($q,
Someasyncservice) {var requestinterceptor = {request:function (config) {var deferred = $q. Defer (); Someasyncservice.doasyncoperation (). Then (function () {//asynchronous operation succeeded, modify config according
Ly ... deferred.resolve (config); The function () {//asynchronous operation failed, modify config accordingly ... deferred.resolve (c
Onfig);
});
return deferred.promise;
}, Response:function (response) {var deferred = $q. Defer (); Someasyncservice.doasyncoperation (). Then (function () {//asynchronous operation succeeded, modify response acc
ordingly. Deferred.resolve (response); }, function () {//asynchronous operation failed, modify response accordingly ... Defe Rred.resolve (response);
});
return deferred.promise;
}
};
return requestinterceptor;
}]);
In the example above, when the request is initiated, if the corresponding deferred is rejected, the HTTP request fails (you may find that the HTTP request did not originate if the packet analysis is carried out). When a request responds, the request fails if the deferred is rejected. (Packet analysis, network requests are returned).
Summarize
The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring certain help, if you have questions you can message exchange.