Verification of the transmission of the HTTP request completed

When utilizing the $http get function in Angular, I am seeking validation that a http request has been successfully sent to our API. Although I am familiar with the .success method, it requires waiting for a response. Is there an alternative method to simply verify that the $http object has indeed initiated the request?

Answer №1

Utilizing a similar method to keep track of the number of requests sent that are awaiting response.

Implement an http-interceptor at the application level:

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

The following is the code for the interceptor (can be customized to handle requests specifically 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; // initialize
        return {
            increase: function() {
                currentRequestCount++;
                $log.log("currentRequestCount ", currentRequestCount);
            },
            decrease: function() {
                currentRequestCount--;
                $log.log("currentRequestCount ", currentRequestCount);
            },
            getCount: function() {
                return currentRequestCount;
            }
        };
    }
])

In any controller, directive, etc., you can utilize RequestCounterService.getCount() to monitor how many requests have been sent without receiving a response yet. This information can be displayed to the user, such as

"There are currently XY requests being processed by the server."

If processing takes too long, it is advisable to address the issue on the server-side, as suggested by James Gaunt in the comments.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for closing the navbar by clicking elsewhere on the page

Is there a way to modify my code in order for the navbar to close when clicking outside of it, while staying open if something inside it is clicked? $(document).ready(function() { $('.nav-btn').on('click', function() { $('.na ...

The attempt to remove the ajax-loaded page while preserving the original div is proving to be

I have a function that is triggered when a link is clicked. This function uses ajax to load a new page over a div. <pre><code> function displayContent(id) { loadPage_signup = "register.php"; loadPage_info = "userinfo.php"; $.aj ...

Trigger a function when <a> is clicked, which will then increment the count by one and reflect this change in the database

The database generates the content of this div ordered by a count number called "cts". Whenever I click on the div, I want the "cts" number to increase by one, and then update the change in the database. This will result in the content changing accordingly ...

Browsing a Collection of Objects within an Array in JavaScript

After making an ajax request to load a JSON file and parsing it to store a reference to the object, I encountered issues while trying to loop through the object due to its structure. Below is a snippet of the JSON data that I am working with: { "marker ...

Tips for utilizing pre-installed validation regulations in VeeValidate 4?

Currently transitioning from Vue 2 to Vue 3, I am interested in utilizing VeeValidate 4 for my validations. However, it seems that the documentation does not provide any information on using built-in rules such as min, max, alpha_spaces, etc. Do I need to ...

How can I use Angular forEach to retrieve both the name of a JSON key and its corresponding

Is there a way to retrieve both the key name and value of a JSON object in Angular using the forEach method? var institute = { "courses": [], "user_type": 3, "institute_name": "sd", "tagline": "sd", "overview": "sd", ...

Javascript's regular expression can be utilized to detect an img tag that has no specified image source (src="")

My specific need is to eliminate all img tags that do not have the attribute "img" specified within them. I attempted to accomplish this using a regular expression - content.replace(/<img[^>]*>/g,""). However, this approach removes all img tags ...

Encountering a Component Exception error in React Native while attempting to implement a Victory chart component

Currently, I am exploring the Victory library for react native to create a line chart for my budgeting application. Below is the code snippet from my Graph component: import React from 'react'; import { View, StyleSheet } from 'react-native& ...

Guide on utilizing Three.js OrbitControl with several objects

I managed to get the orbit control feature working, but I am facing an issue where controlling one object also ends up controlling all three objects on the page. Additionally, pan/zoom functionality does not seem to work at all with the OrthographicCamera. ...

Add a click event listener to all elements with a specific class

How can I register a click event for all elements found with this specific request? I attempted the following code, but it seems that the click event is not functioning as expected: $("#content .item").each(function() { $(this).click(function(){ ...

I'm experiencing difficulty getting my code to function properly when adding or removing classes with Bootstrap Glyphicons

Recently, I decided to play around with bootstrap's glyphicons. By utilizing Jquery's addClass and removeClass functions, I tried to smoothly transition from one glyphicon to another. Here is the code snippet: var glyphOn = true; //The glyphO ...

Step-by-Step Guide on Building a Globe with Global Map using three.js

While trying to create a sphere with a world map using three.js, I encountered an issue where the output displayed only a black screen. https://i.sstatic.net/LZFeC.png Below is the code I used: <!DOCTYPE html> <html> <head> ...

Exploring Array Iteration: Navigating through Arrays with the .map Method in React and Vue

I am currently using Vue after coming from a React background. In React, there is a method called .map that allows you to render a component multiple times based on the number of items in an array and extract data from each index. Here's an example: f ...

Tips for modifying the response of an ExpressJS server following a timeout on a POST request

Currently, I'm in the process of creating a server using Node.js and ExpressJS. The issue arises when the client sends a POST request instructing the server to control an external device's movement either up or down. My goal is for the server t ...

Getting an undefined error value in the ionic overlay side menu - what could be causing this issue?

My current challenge involves displaying the overlay side menu. I have written code to achieve this, adding a menu icon in the header that opens the overlay side menu when clicked, and closes it when clicked outside. However, I encountered an issue where ...

What is the best way to organize the information within an array or JSON?

I have a unique process in my NODE script where I download raw data that needs to be transformed multiple times. First, it downloads as a .txt file, then gets converted to CSV, followed by JSON transformation and finally ends up as XML format. This is beca ...

Exploring the World of D3.js with an Interactive Example

Struggling to grasp D3, I'm having difficulty executing the circle example. http://mbostock.github.com/d3/tutorial/circle.html I aim to run the part where the circles change colors and sizes. I simply copied and pasted the example but can't fi ...

Express: fetch not capable of setting cookie

I am implementing a cookie setting feature with Express, using the code snippet below: app.use(require('cookie-parser')()); app.get('/a', function (req, res) { console.log(req.cookies); res.cookie('aaa', 'bbb&apo ...

Encountered an issue while trying to synchronize Protractor with the page when an alert appeared during a page refresh

Upon refreshing the page, I encounter an error and receive the following alert: Failed: Error occurs while waiting for Protractor to synchronize with the page: "both angularJS testability and angular testability are undefined. This may be due to eith ...

The AJAX function is failing to return false

I found this code snippet in my index.html file: <form> <input onkeyup="firstnamecheck(this.value)" type="text" name="firstname" id="Start" class="Inputs" /> <button type="submit" name="Murad" id="tester" title="Register">Register</b ...