In an MVC based application, we switch pages without getting refreshed. For showing data in our current view, we usually load updated JSON objects by hitting API calls and we do so by using $http services of angular js. So in some cases, we don’t want a user of an application to hit API calls more then once, otherwise, he/ she will be left with a stack of pending API calls overlapping data sets. We can prevent such user practices by using following two ways:
Let’s show a full page loader when a user makes an API hit. Loader gets visible when $http call is hit and the loader will be visible on whole page unlit current request is completed. So, indirectly we restricted a user from doing any other task until the previous request is completed :P.
The Legit Way:
We can simply cancel previous requests when ever user switch the view from one to other. Whenever the user moves from one view to other previous pending Http requests will cancel out automatically.
To get this done we need to include module named angular-cancel-on-navigate by AlbertBrand
This works on angular js promise algorithms.
Let’s Implement this module in our application.
Step 1) Download clone package and include Module, Service, and Interceptor in you Index.html
<script src="js/angularCancelOnNavigateModule.js"></script> <script src="js/httpPendingRequestsService.js"></script> <script src="js/httpRequestTimeoutInterceptor.js"></script>
Step 2) Now we need to inject dependency in application module as follows
angular .module('myApp', [ ... 'angularCancelOnNavigateModule' ])
That's it now when ever you switch URL previous $http request will cancel out.