I am developing an application with AngularJS and I need to define a hook ( handler ) that is executed before and after each ajax transaction performed with the object $http
. I have seen that for jQuery there are ajaxStart and ajaxStop methods , but obviously they don't work in this case. Is there a direct equivalent, or can the same effect be achieved somehow, in AngularJS? The documentation doesn't seem to mention anything about it.
Note that I want the code to be executed for all transactions, not for a specific one (in this case I would include the code in the delegates .then
).
As @rnrneverdies says you can use the $interceptor.
What is the $interceptor?
It
$httpProvider
contains an array of interceptors, an interceptor is a simple factory service that is in charge of intercepting the request, either when it is starting (Doing an Ajax Start), when it is returning the response (Ajax Stop) or when it fails, this tells us it is used for error handling or processing something before/after the request. One of the ways to create it is as follows:You create a Service factory
Note:
The methods that you see in the upper part as they are
'request'
,'responseError'
among others is the way how Angular captures that the request is being made or that it is giving an error. As you can see there are only those 4 methods according to the documentation .How do I invoke my interceptor?
You just need in an app.js or where your module is to create the angular config and call it
$httpProvider.interceptors
like this:As they already told you, it is done with Interceptors
Almost all of us use them for the same thing, for example to be able to locate the code of the actions to be carried out in each ajax request (be it to authenticate - example with JWT, block the ui with loading elements, etc)
I put another example, organizing in modules For example if we have modularized our app in several files (no matter how many modules can be in the same file)
myApp.js
As you can see, interceptors can be added, it is an array of services. You would have to have a file previously loaded with loadingInterceptor.factory.miApp.js
It seems to me that the code is a little more "readable", and you can separate the Service Factories to intercept, modularizing your AngularJS app
Links that can help or guide you