AngularJS not displaying loader during AJAX request

While utilizing ajax requests with $http, there seems to be a delay due to the server operation taking longer than expected. I have implemented a loader to display while processing the request, but unfortunately it is not showing up on the page. Even after trying various methods, the issue persists.

Index.html

<body ng-app="app">

    <!-- loader, can be used on multiple pages-->
    <div class="loading loader-quart" ng-show="isLoading"></div>

<!--         my logic       --> 

</body>

addCtrl.js

//function for sending attributes to server using service
    $scope.add = function () {
        if ($scope.Option == 'newInstance')
            $scope.singleObject.FK_Name = 'MetisEmptyTemplate';
        $rootScope.isLoading = true;
        var featuresList = websiteService.getUpdatedTree($scope.treeDataSource);
        var formData = new Website("", $scope.singleObject.Name, $scope.singleObject.DisplayName, $scope.singleObject.Description, $scope.singleObject.State, "", $scope.singleObject.FK_Name, $scope.singleObject.Email, featuresList);

        websiteService.addwebsite(formData);
        $rootScope.isLoading = false;
    }

websiteService.js

//service for adding website
    this.addwebsite = function (website) {
        $http({
            method: 'POST',
            url: $rootScope.url + 'Add',
            data: JSON.stringify(website),
            contentType: 'application/json'
        }).success(function (data) {
            alert(data);
        }).error(function (data, status, headers, config) {
            //alert(data);
        });
    }

After setting isLoading as "true" at the start and then toggling it to "false" once the request is complete, the loader should appear correctly. What could be causing the code to malfunction?

Answer №1

Your websiteServices code is designed to run asynchronously, meaning that the loader will appear and disappear quickly.

To properly handle asynchronous code in the controller, you need to return a promise from the service and include the hiding of the spinner within a callback function using .then().

Service:

this.addwebsite = function (website) {
    var deferred = $q.defer();
    $http({
        method: 'POST',
        url: $rootScope.url + 'Add',
        data: JSON.stringify(website),
        contentType: 'application/json'
    }).success(function (data) {
        alert(data);
        deferred.resolve(data);
    }).error(function (data, status, headers, config) {
        //alert(data);
        deferred.reject(data);
    });
    return deferred.promise
}

Controller:

websiteService.addwebsite(formData).then(function(){
    $rootScope.isLoading = false
});

Answer №2

    function addMliveResponse(data){
        var post=$q.post();
        var url='/mlive-portlet/rest/mliveResponseService/addmLiveResponse';
        httpRequest(url,data).then(function(result){
                post.resolve(result.data);
        },function(error){
            post.reject(error.data);
        })
        return post.promise;
    }

Answer №3

If you need to handle requests, I believe utilizing an interceptor is the most efficient way to manage showing and hiding a loader.

In this code snippet, I am employing a loader service to turn on and off the loader.

For example:

// http.config.js file
export function httpConfig($httpProvider, AuthInterceptProvider) {
  'ngInject';
  AuthInterceptProvider.interceptAuth(true);

  // created for showing loader
  $httpProvider.interceptors.push(function (loaderService, $q) {
    'ngInject';
    return {
      'request': function (config) {
        loaderService.switchLoaderModeOn();
        return config;
      },

      'requestError': function (rejection) {
        loaderService.switchLoaderModeOff();
        return $q.reject(rejection);
      },

      'response': function (response) {
        loaderService.switchLoaderModeOff();
        return response;
      },

      'responseError': function (rejection) {
        loaderService.switchLoaderModeOff();
        return $q.reject(rejection);
      }
    };
  });
}

// in your module.js file
import {httpConfig} from './config/http.config';

.config(httpConfig)

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

Encountering an error when setting up a React-TypeScript ContextAPI

I am currently attempting to understand and replicate the functionality of a specific package found at: https://github.com/AlexSegen/react-shopping-cart Working within a React-Typescript project, I have encountered challenges when creating the ProductCont ...

"Mastering the art of traversing through request.body and making necessary updates on an object

As I was reviewing a MERN tutorial, specifically focusing on the "update" route, I came across some interesting code snippets. todoRoutes.route('/update/:id').post(function(req, res) { Todo.findById(req.params.id, function(err, todo) { ...

Using React to integrate Zurb Foundation's slider by binding moved.zf.slider

Update: I have included the complete code as requested. There are a few modifications from the original version. I am attempting to integrate the foundation slider with react and ES6. The slider is supposed to trigger an event named moved.zf.slider when i ...

Tips for transferring information to an input field's value

There's an input box with an empty value that needs to be filled with data. <input type="text" value="" class="box"> $('.skills-tags').on('click', function(){ var value = $(".skills-tags").val(); $('.label-pr ...

What advantages can I expect for my client-rendered pages with Gatsby's Client Side Routing?

For a small site I developed, I utilized Gatsby for static content. However, for certain dynamically rendered content, I opted to employ client-only routes in Gatsby. Although I implemented a Header, Footer, and a specific font on my static site, these sa ...

Limiting the size of image uploads in AWS S3

Currently, I am attempting to go through the steps outlined in this repo, which involves utilizing nextjs and AWS S3 for image uploading. However, one thing that is puzzling me is the limitation of 1MB on image sizes. I'm curious as to why this restri ...

What is the best way to send a prop to my home route following a redirect?

I am working with react-router-dom and I want to pass :id to my first route (/) when redirecting. This is important so that I can access :id in my Interface component and maintain consistent URL structure for my single-page application. Is it feasible to a ...

The presence of certain characters is leading to problems in the console

Similar Question: Escaping a String for JavaScript Usage in PHP? The characters in my text are causing errors. When I input special characters such as: !\"$%^&()-=\'.,:;/?#~/\\>< An error saying "Syntax error ...

Customizing the Switch component individually for each item fetched from an API in React Native

I'm struggling with setting the switch button individually for each item in my API. Despite trying multiple solutions, none of them seem to work for me. const results = [ { Id: "IySO9wUrt8", Name: & ...

Unlocking the Power of jQuery's toggle Method for Dynamic Functionality

For my project, I require numerous jQuery toggles to switch between text and icons. Currently, I am achieving this by using: $("#id1").click(function () { //Code for toggling display, changing icon and text }); $("#id2").click(function () { //Same co ...

A function that handles HTTP request and response

In order to decrypt data, I need to retrieve the encrypted response by hitting a specific URL and then use that encrypted data along with a key to decrypt it. Initially, I attempted to fetch the data response using POSTMAN, but all I got back was a series ...

Leveraging JavaScript event handlers within a progress wizard located within an update panel

I need assistance with implementing a password strength meter for a textbox within a wizard control. The issue I'm facing is that the password box does not become visible until step 4, preventing me from registering an event handler onload(). Placing ...

Cross-domain AJAX/XDomainRequest being sent to a web service

I recently dedicated a significant amount of time to scouring through numerous posts on various platforms, and as a result, I have come up with the following code snippet: function post_cors(vars) { // cross domain AJAX posting - needs work to f ...

The event listener for 'annotations.create' in the PSPDFKIT instance does not include the required annotation type

I'm facing difficulties with integrating pspdfkit to properly create and display my annotations. My goal is to create annotations in the following manner: instance.addEventListener("annotations.create", createdAnnotations => { ...

Encountering a script error when upgrading to rc4 in Angular 2

After attempting to update my Angular 2 version to 2.0.0.rc.4, I encountered a script error following npm install and npm start. Please see my package.json file below "dependencies": { "@angular/common": "2.0.0-rc.4", "@angular/core": "2.0.0-rc.4", ...

Binding an event to an Angular 2 component directly within its selector code

Looking at my Angular 2 component: import { Component, ElementRef, Renderer } from '@angular/core';; @Component({ selector: 'my-button', templateUrl: 'button.html' }) export class ButtonComponent { private text: string ...

What do you call the syntax %< ... >%?

Observed zoomInAnimation : true, zoomOutScale : false, templateLegend : "<ul class=\"<%=type.toLowerCase()%>-legend\"><% for (var j=0; j<sections.length; j++){%><li><span style=\"background-color:<%=section ...

Is there a way to efficiently process multipart/formdata, application/json, and text/plain within a single Express handler?

Operating an express demo server that mirrors the client's POST requests back to it is a part of an educational practice. In this exercise, the client makes a POST request using the fetch API, like so: fetch('http://localhost:5000/', { m ...

Ways to execute the pdf.js node demonstrations?

I've been attempting to run the pdf.js node examples, specifically getinfo.js. Unfortunately, I encountered an issue that resulted in the following error: C:\Repositories\pdf.js>node getinfo.js node:internal/modules/cjs/loader:1080 thro ...

JsDoc presents the complete code instead of the commented block

I have a VUE.JS application that needs to be documented. For .VUE components, we are using Vuese. However, when it comes to regular JS files like modules, we decided to use JsDoc. I have installed JsDoc and everything seems fine, but when I generate the HT ...