$httpAngularJS $http
Service allows us to communicate with the background by sending HTTP requests. In some cases, we want to be able to capture all requests and operate before sending them to the server. In other cases, we want to capture the response and process it before the completion call is complete. A good example is handling global HTTP exceptions. Interceptors (interceptors) emerged. This article will introduce AngularJS interceptors, and give a few useful examples.
What is an interceptor?
$httpProvider
There is an interceptors
array, and the so-called interceptor is simply a generic service factory registered to the array. The following example shows you how to create an interceptor:
<!-- lang: js -->module.factory(‘myInterceptor‘, [‘$log‘, function($log) { $log.debug(‘$log is here to show you that this is a regular factory with injection‘); var myInterceptor = { .... .... .... }; return myInterceptor;}]);
It is then added to the array by its name $httpProvider.interceptors
:
<!-- lang: js -->module.config([‘$httpProvider‘, function($httpProvider) { $httpProvider.interceptors.push(‘myInterceptor‘);}]);
Interceptors allow you to:
To request
intercept a request by implementing A method: The method $http
executes before the request is sent back to the backend, so you can modify the configuration or do other things. The method receives the request configuration object (requests config objects) as a parameter, and then must return the configuration object or promise
. If an invalid configuration object is returned or promise is rejected, the $http
call fails.
To response
intercept a response by implementing a method: The method $http
executes after receiving a response from the background, so you can modify the response or do other things. The method receives the Response object (response object) as a parameter, and then must return the response object or promise
. The response object includes the request configuration, the header (headers), the State (status), and the data from the background. If an invalid response object is returned or promise is rejected, the $http
call fails.
To requestError
intercept a request exception by implementing a method: sometimes a request fails to send or is rejected by the interceptor. Request exception interceptors capture requests that were interrupted by a previous request interceptor. It can be used to restore the request or sometimes to undo the configuration that was made before the request, such as closing the progress bar, activating the button and the input box, and so on.
To responseError
intercept a response exception by implementing the method: sometimes our back-end calls fail. It is also possible that it was rejected by a request interceptor or was interrupted by a response interceptor. In this case, the response exception blocker can help us to restore the background call.
The ANGULARJS offers four interceptors, two of which are successful interceptors (request, response), and two failure interceptors (Requesterror, Responseerror).
Angular.module ("myApp", []) . Factory (' Httpinterceptor ', [' $q ', ' $injector ', function ($q, $injector) { var Httpinterceptor = { ' Responseerror ': function (response) { ... Return $q. Reject (response) , ' response ': function (response) { ... return response; }, ' request ': function (config) { ... return config; }, ' Requesterror ': function (config) { ... Return $q. Reject (config); } } return httpinterceptor; }
Therefore, we can use the interceptor to determine the login and permission issues.
The $rootScope in the code. User is logged in and put the information on the global Rootscope, convenient for other places to use, $rootScope. Defaultpage is also the default home page, which is written to Rootscope when initialized.
$rootScope. $on ( ' $stateChangeStart ', function (event, ToState, Toparams, FromState, Fromparams) { if (tostate.name== ' login ') //if the login screen is entered allows //if the user does not exist if (! $rootScope. user | | ! $rootScope. User.token) {event.preventdefault (); //cancel default jump behavior $state. Go ( " Login ", {from:fromstate.name,w: ' Notlogin '}); //jump to login interface }
There are also users logged in, but the login time-out, there is to increase the background interface to judge to enhance security. Cannot rely entirely on local logic
We add a user interceptor in the model, judge the error code in the Rensponseerror, throw the event to contoller or view to handle
App.factory (' Userinterceptor ', ["$q","$rootScope",function($q,$rootScope) {return {Requestfunction(config) {config.headers["TOKEN"] =$rootScope. User.token; return config;},Responseerror:function(response) { var data = Response.data;Determine the error code if it is not logged in if (data["ErrorCode"] = ="500999") {Clears the user's local token store information, if $rootScope. User = {token://global events to facilitate other view to get the event, and give appropriate hints or processing $rootScope. $emit ( "userintercepted", }//if login timeout "ErrorCode"] = = "500998") { $rootScope. $emit (} return $q. Reject (response);
Don't forget to register the interceptor in Angularjs Config.
App. Config (($httpProvider) {$httpProvider. Interceptors.push (' userinterceptor ');}); |
Finally handle the error event in the controller
$rootScope. $on (' userintercepted ', function (errorType) { //jump to the login screen, where I record a from so that you can automatically jump to the interface before login $state. Go ("login", {from: $state. Current.name,w:errortype});});
Finally, you can do more details in the Logincontroller.
If the user is already logged in, immediately jump to a default home page without having to sign in if ($rootScope. User.token) { $state. Go ($rootScope. defaultpage); return;}
In addition, after the login successful callback can also jump to the previous interface, that is, the above record from
var from = $stateParams [' from ']; $state. Go (from && from! = "Login"? From: $rootScope. defaultpage);
AngularJs HTTP response Interceptor for login, permission check