Ensure that the loader remains visible until all data has been successfully retrieved from the AngularJS service

Currently, I am facing an issue with the implementation of angularjs ui-router for state transitions along with a loader assigned to each view. The problem arises when moving from one state to another and the loader disappears before all the content from the web service is loaded and other get requests are completed. This is my first attempt at using angularjs's ui-router.

In an effort to resolve this issue, I have experimented with different methods:

app.run(function($rootScope,$cookies){
  // Triggered when the transition begins
  $rootScope.$on('$stateChangeStart',function(e, toState, toParams, fromState, fromParams){
      $rootScope.loading = true;
  });

  // Triggered once the state transition is complete
  $rootScope.$on('$stateChangeSuccess',function(e, toState, toParams, fromState, fromParams){
      $rootScope.loading = false;
  });
});

I also attempted to use the resolve method like so:

...
.state('loan-new',{
   url: '/loan-new/:id',
   templateUrl: BASE_URL+'js/pages/loan-new.html',
   controller: 'LoanController',
   resolve: {
      loanNew: function($q, client, $stateParams, $http) {
        var defer = $q.defer();
        if(client.getAllInformation($stateParams.id) !== undefined) 
        {
          $http.get(BASE_URL+'client-loan-types').success(function(data) {

          })
          .then(function(){

            client.getAllInformation($stateParams.id).then(function(data) {
              defer.resolve(data);
              console.log('APP DATA');
              console.log(data);
            });

          });
        } 
        else 
        {
          defer.reject(data);
        }

        return defer.promise;
    }
  }
})
...

Lastly, I tried the following code without success:

app.controller('LoadingController', ['$scope', '$http', '$rootScope', '$stateParams', 'client', '$q', function($scope, $http, $rootScope,  $stateParams, client, $q) {

  $rootScope.loading = true;

  $scope.$on('$viewContentLoading', function(event, viewConfig){
     console.log('content loading: ', event, viewConfig)
     return client.getAllInformation($stateParams.id);
  });


  $scope.$on('$viewContentLoaded', function(event) {
    $rootScope.loading = false;
    console.log('loaded loaded loaded');
  });
}]);

HTML

    <!-- CSS Loader -->
    <div id="overlay" ng-show="loading">
        <div class="sk-cube-grid">
          <div class="sk-cube sk-cube1"></div>
          <div class="sk-cube sk-cube2"></div>
          <div class="sk-cube sk-cube3"></div>
          <div class="sk-cube sk-cube4"></div>
          <div class="sk-cube sk-cube5"></div>
          <div class="sk-cube sk-cube6"></div>
          <div class="sk-cube sk-cube7"></div>
          <div class="sk-cube sk-cube8"></div>
          <div class="sk-cube sk-cube9"></div>
        </div>
        <p>Loading...</p>
    </div>

<div class="content-wrapper ng-cloak" ng-controller="LoadingController">
    <div class="container wrap-content ng-cloak" ui-view>

    </div>
</div>

Service

app.factory('client', ['$http','$q',function($http,$q){ 
    var client = {};//empty oject that will store multiple functions

 ...
 //get all of the client's personal information
 client.getAllInformation = function(ucin){
      var deferred = $q.defer(); //create promise to be completed for getting a client's information
      $http.get(LOSAPI+ucin).success(function(data){
            deferred.resolve(data.data); //when success resolve the promise by accepting the data from the web serivces
      }).error(function(){
           return deferred.reject(); //promise was not completed for some reason
      });
      return deferred.promise; //return the promise
 };

    return client
}]);

 ...

If anyone can provide some guidance on how to tackle this issue effectively, it would be highly appreciated. Thank you.

Answer №1

Make sure to set $rootScope.loading = false once your API call is complete.

 client.retrieveClientData = function(ucin){
      var promise = $q.defer(); //create a promise for fetching the client's information
      $http.get(APIURL+ucin).success(function(data){
            promise.resolve(data.data); //resolve the promise with the fetched data
         $rootScope.loading = false;
      }).error(function(){
           return promise.reject(); //reject the promise if there was an error
      });
      return promise.promise; //return the promise object
 };

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

Removing a Dynamic Element in ReactJS

--CustomFieldSection.js-- import React, { Component } from 'react'; import CustomField from './CustomField.js'; class CustomFieldSection extends Component{ constructor(props){ super(props); this.stat ...

Execute sequential animations on numerous elements without using timeouts

I'm currently working on developing a code learning application that allows users to write code for creating games and animations, similar to scratch but not block-based. I've provided users with a set of commands that they can use in any order t ...

Troubleshooting Issue: Failure of Ajax Script to Display Saved Data in Edit Function

Whenever I clicked on the Edit icon in the action column of my data tables, the saved data did not display as expected. I noticed that this issue was only occurring for file input types, while it worked properly for text input types. In the Blade file Ad ...

Experiencing a dependency injection issue when attempting to include ngRoute into the dependencies

In my AngularJS app, I have included the ngRoute dependency for routing and created a service for making REST calls. However, when I try to inject the dependency with ngRoute, I encounter the following error: angular.min.js:6 Uncaught Error: [$injector:mo ...

Switching from PHP to jQuery or JavaScript can make for a

I've been attempting to convert this PHP code to jQuery or JavaScript without success. I'm still learning about jQuery and JavaScript Check out the original PHP code: <?php // Set timezone date_default_timezone_set('UTC'); ...

Creating intricate structures using TypeScript recursively

When working with Angular and TypeScript, we have the power of generics and Compile-goodness to ensure type-safety. However, when using services like HTTP-Service, we only receive parsed JSON instead of specific objects. Below are some generic methods that ...

Collaborative spreadsheet feature within a browser-based software platform

I am using an Angular-based SPA for my web application. My goal is to be able to open an Excel file within the application itself. Currently, I have a menu button or link that is linked to a specific path, for example //192.168.10.10/sharedExcels/myExcel. ...

renewing a div element without the need to reload the entire webpage

I'm currently developing a setup process for configuring a database. My goal is to allow the user to progress through each phase without having to refresh the page. However, I've encountered an issue while trying to implement the .load() function ...

Chrome's keyup event restricts the use of arrow keys in text fields

Could you please test this on Google Chrome browser: jQuery('#tien_cong').keyup(function(e) { jQuery(this).val(jQuery(this).val().replace(".", ",")); var sum = 0; var tien_cong = jQuery('#tien_cong').val(); tien_cong = tien_ ...

Obtain the name of the object method from inside the method itself

Imagine having an object like this: var app = {} inside which there is a method: app = { initialize: function () { } } Is it possible to retrieve the name of the method 'initialize' from within the initialize() function without explicit ...

Struggling to incorporate pagination with axios in my code

As a newcomer to the world of REACT, I am currently delving into the realm of implementing pagination in my React project using axios. The API that I am utilizing (swapi.dev) boasts a total of 87 characters. Upon submitting a GET request with , only 10 cha ...

Utilize jQuery to load AngularJS libraries into your web application

Trying to incorporate AngularJS into a jQuery-built webpage has been my latest challenge. While the rest of the site was developed using jQuery, I wanted to tap into the potential of AngularJS for a specific page. That's when I decided to do this: jQ ...

Struggling to adjust the timeout to exceed 60 seconds

I have been attempting to set a timeout for 120 seconds or more, but no matter what I try, the requests are timing out after only 60 seconds. Things I have tried include: $.ajax({ url: URL, timeout: 120000, success: function(html){ co ...

Add to the current values of the REACT Form template property

I am new to working with REACT and I have been exploring whether it is possible to append a REACT Form control property value in order to enhance its functionality. To streamline the validation process, I have created a validation template that leverages ...

Implementing ExpressJS with MongoDB on a MERN Development Stack

After configuring my ExpressJS & MongoDB client and running Nodemon, I consistently encounter the following warning: "DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the ...

Tips for validating Angular form group input depending on the value of another input within the form?

I am facing an issue with form validation in my Angular version 8 application. I need to validate a form based on the following rules: If a file is uploaded (even if just clicking the button without selecting a file), then the Reason input is not required ...

Investigating High Energy Usage on Vue.js Websites: Identifying the Root Causes

My Vue.js application has grown to be quite large with over 80 .vue components. Users have been complaining about their phone batteries draining quickly and Safari displaying a "This webpage is using significant energy..." warning. I have tried investigat ...

The StreamingTextResponse feature is malfunctioning in the live environment

When I share my code, it's an API route in Next.js. In development mode, everything works as expected. However, in production, the response appears to be static instead of dynamic. It seems like only one part of the data is being sent. I'm puzzl ...

Unable to access the inner object using key-value pair in Angular when working with Firebase

Within my json object, there is an inner object labeled data, containing {count: 9, message: "9 sites synced"} as its contents - also in json format. My objective is to extract the value from message, rather than count. Provided below is the temp ...

Trouble Deciphering JSON Array Using Eval Function

I'm facing an issue with two files in my project - one is a PHP file containing an array that is echoed using json_encode, and the other is a JavaScript file containing various functions for a webpage. One particular function in the JavaScript file is ...