简体   繁体   中英

Confirm HTTP Request Sent

I am using the $http get from Angular, I want to confirm that a http request is sent to our API. I am aware of the .success method but this waits for a return, is there a way to just get the $http object to confirm the request has been sent?

I used something similar to track number of requests sent, which are waiting for response.

Add an http-interceptor on app level:

.config(['$httpProvider',
    function($httpProvider) {
        $httpProvider.interceptors.push('RequestCounterInterceptor');
    }
])

The code of interceptor (you can modify it to handle just requests to your API's url):

.factory('RequestCounterInterceptor', ['RequestCounterService', '$q',
    function(RequestCounterService, $q) {
        return {
            'request': function(request) {
                RequestCounterService.increase();
                return request;
            },
            'requestError': function(request) {
                RequestCounterService.increase();
                return $q.reject(request);
            },
            'response': function(response) {
                RequestCounterService.decrease();
                return response;
            },
            'responseError': function(response) {
                RequestCounterService.decrease();
                return $q.reject(response);
            }
        };
    }
])

The service:

.service('RequestCounterService', ['$log',
    function($log) {
        var currentRequestCount = 0; // init
        return {
            increase: function() {
                currentRequestCount++;
                $log.log("currentRequestCount ", currentRequestCount);
            },
            decrease: function() {
                currentRequestCount--;
                $log.log("currentRequestCount ", currentRequestCount);
            },
            getCount: function() {
                return currentRequestCount;
            }
        };
    }
])

Then anywhere in you controller, directive... you can use RequestCounterService.getCount() to see how many requests have been sent and did not received response yet. You could display a message to user like There are currently XY requests being processed by the server or similar.

But in case the processing takes too much time, you should solve your issue server-side as James Gaunt proposed in comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM