Notification for background processing of $http requests

I am searching for a solution to encapsulate all my AJAX requests using $http with the capability to display a loading gif image during processing. I want this functionality to extend beyond just $http requests, to cover other background processing tasks as well.

The reason for my inquiry is that it feels inelegant to constantly toggle my processingIndicator between true and false in my success function.

One potential approach I'm considering involves a higher-order function that takes another function as an argument. This function would set the processingIndicator to true, execute the provided function, and then switch back to false.

function processAjaxRequestSuccessFn(fooFn){
  // display processing indicator
  fooFn();
  // hide processing indicator
}

Then I could use:

$http.get(...).then(processAjaxRequestSuccessFn, processAjaxRequestErrorFn)

This method, while effective, requires me to call the function every time I need to notify the user of processing actions, which is not very efficient.

I am exploring options to automate this workflow more seamlessly.

Update:

Another concept I am considering is extending $http with custom methods like get, post, etc., or creating a specialized service with similar functionality. However, these approaches also lack elegance.

Answer №1

Implement an interceptor with the code example below...

app.factory('HttpInterceptor', ['$q', function ($q) {
    return {
        'request': function (config) {
            /*...*/
            return config || $q.when(config);   // -- start request/show gif
        },
        'requestError': function (rejection) {
            /*...*/
            return $q.reject(rejection);
        },
        'response': function (response) {       // -- end request/hide gif
            /*...*/
            return response || $q.when(response);
        },
        'responseError': function (rejection) {
            /*...*/
            return $q.reject(rejection);
        }
    };
}]);

app.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push('HttpInterceptor');
    /*...*/
}]);

This approach allows you to inject centralized logic at specific points in the http request process, utilizing callbacks provided by the API. You can customize reusable request logic as needed within this structure. Refer to the interceptors section of the AngularJS $http documentation for further details.

Answer №2

After implementing AngularOverlay, I was able to efficiently showcase a loading icon during ongoing HTTP requests. Simply grab the necessary files, adhere to the provided guidelines, and watch it seamlessly in action.

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

Capture a screenshot of the icons

I'm curious about displaying specific parts of images in a React Native application. class InstaClone extends Component { render() { return( <View style={{ flex:1, width:100 + "%", height:100 + "%" }}> <View style={st ...

What is the process for identifying children records of a parent (Adonis Lucid Many-to-Many) that match a specific criteria?

I am currently searching for the presence of specific Permissions within a single parent Role in a many-to-many relationship. const roles = await Role .query() .preload('permissions') this.role = roles.find(role => role.id === someid) co ...

How to Implement Click Actions on Elements in AngularJS

Just starting out with angularjs and I have a scenario with jQuery. handleClick(); function handleClick() { var doubleClick = false; $('#text span.word').on('click', function() { var that = this; setTimeout(funct ...

What is the mechanism behind the operation of the inherits feature in Node.js?

The following code snippet illustrates how the inherits function works in node.js: exports.inherits = function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, ...

Display or conceal toggle in ruby utilizing jQuery

I'm facing an issue with the functionality of a button that is meant to hide and show a form using jQuery. Initially, I added a path to signup in the button so that it would display and function properly. Now, when I click the button, the form shows u ...

The Bootstrap modal window refuses to shut down

In my React application, I am utilizing Bootstrap modal functionality. One specific requirement is that the modal window should remain open when clicking on the modal backdrop. To achieve this, I have implemented the following code: $(".modal").modal({"ba ...

Receiving array data in a Javascript function and storing it within a variable

Hello everyone, please take a look at my code below. I am attempting to pass PHP array values to a JavaScript function. When I run the script, I receive alerts for parameter0=1, parameter1=2, and parameter2=3 separately. What I am trying to achieve is to ...

Using jQuery, Ajax, JSON, PHP, and encountering a parsererror

I'm currently facing an issue while attempting to submit a form to a PHP file using $.ajax in jQuery. I've been sending the entire form data as JSON, but upon trying to retrieve the response, I keep encountering the 'parsererror'. Can a ...

Enabling table row scrolling with keyboard navigation in React

Struggling to figure out how to make my table scroll while navigating through the rows using the onKeyDown event. It seems that the event isn't updating when using the keyboard, even though the highlighting of the selected row with selected is working ...

Switch image formats to webp using react js

Utilizing the react-dropzone package, I aim to incorporate images into my application. To achieve this, I must send the images to a firebase server after managing image conversions. Whilst browsing through YouTube tutorials, I came across a guide demonstr ...

"Encountering a hiccup with the Firebase service worker in Messaging and Firebase

I am interested in developing a small web application to explore the capabilities of Firebase Cloud Messaging for web apps. My intention is to utilize Firebase Hosting as the hosting platform for my app. ISSUE: Upon allowing the notification pop-up on my ...

Tips on deleting CSS comments from a CSS file

Currently, I am utilizing nextjs + reactjs. My objective is to eliminate all CSS comments from my existing css file. Despite using next-purgecss in order to get rid of unnecessary CSS code, the comments are still persisting. What could be the reason behind ...

What could possibly be causing my code to execute multiple times?

Within my code, I have the following function that is triggered when the document is ready: $('#file_upload_form').submit(function(){ // show loader [optional line] //if(document.getElementById('upload_frame') == ...

The fitBounds() method in Google Maps API V3 is extremely helpful for adjusting

I am trying to display a map on my website using this code: function initialize() { var myOptions = { center: new google.maps.LatLng(45.4555729, 9.169236), zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP, panControl: true, mapTyp ...

The issue with AngularJS multiple $http requests failing to fetch accurate data

I'm having issues with my AngularJS controller and service modules. I want to refresh custController.allCustomers after adding a new customer so that the UI displays the new data. However, when I call custController.createCustomer, the new customer do ...

Using three.js inside Colab

Here are some examples showcasing bi-directional communications between Python and JavaScript in Google Colab: I'm trying to get this simple three.js demo to work in Colab. Any tips? Despite the seemingly straightforward source code, I'm facing ...

Material-UI Issue: Why is makeStyles not working as expected?

Encountered Error: TypeError: Object(...) is not a function 13 | import { connect } from 'react-redux'; 14 | 15 | > 16 | const useStyles = makeStyles(theme => ({ 17 | ...theme 18 | })); 19 | Code Snippet: const useStyles ...

Is there a way to switch an element across various pages within Ionic 3?

Is it possible to exchange information between two pages using logic? I have successfully implemented a checklist, but I am unsure how to add a success/error icon next to the Room name on the 'verifyplace.html' page after invoking the goToNextPa ...

Selenium WebDriver producing unexpected results with getTitle() method

Currently, I am executing an automated test script in a selenium-webdriver environment using Phantomjs. My approach involves running the script through node.js, rather than utilizing Python or C#. The steps I took to set up the environment are outlined b ...

Can you upload a file using the MaterialUI Upload Button in React and then send it to Firestorage?

Hi everyone! I recently implemented MaterialUI's Upload Button in my project, which you can find here: https://material-ui.com/components/buttons/ Below you will see the code snippet where I have integrated this button and now I am trying to upload a ...