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

How can I programmatically trigger the searchbox 'places_changed' event using angular-google-maps syntax?

I am looking for a way to programmatically trigger the places_changed event of the angular-google-maps searchbox, instead of relying on manual entry. How can I achieve this? I attempted using the following vanilla JS solution: google.maps.event.trigger(s ...

Capturing and saving detailed hand-drawn artwork in high resolution

Is there a cutting-edge solution available for capturing hand-drawn sketches (from a tablet, touch screen, or iPad-like device) on a website using JavaScript and saving it on the server side? Essentially, I am looking for a mouse drawing canvas with a hig ...

The content within the tab is currently being loaded

Incorporating jQuery UI tabs into my webpage, I encounter a delay of 5-6 seconds when clicking on a tab as it triggers an ajax call for preparing and displaying content. The screen stays idle during this time, leading to user confusion. I am seeking a sol ...

Customize the position of the Datetimepicker

Is there a way to customize the position of the datetimepicker, ensuring that it stays within the visual boundaries without getting cut off? I need help with this. ...

What is the best way to incorporate an interval within a customized filter?

I customized a date filter to run like a clock every second by setting an interval. Thank you for your help! Below is the code I used: app.filter('DateGap', function() { return function update(input, optional1, optional2) { var t1 = ...

Substitute all web links contained within the DIV

Is there a way to change the URLs within a specific DIV? Here's an example of what I want to do: <div id="SearchList"> <a href="www.google.com/up">up</a> <a href="www.google.com/down">down</a> <a href="www.google.com/ ...

Is it possible to apply search filters within a child component in Angular?

I have a situation where I am passing data from a parent component to a child component using *ngFor / @input. The child component is created multiple times based on the number of objects in the pciData array. pciData consists of around 700 data objects, ...

Steps to remove a specific child element using jQuery:

CSS: <h1><br style="clear:both;"></h1> I am currently working on a project that involves using the Wikipedia API. One issue I've run into is cleaning up the raw HTML output from Wikipedia, specifically dealing with removing a speci ...

Manipulate HTML content from JSON data in JavaScript without using jQuery

The information stored in the texts.json file: [{ "PageTextKeyId": 1, "PageTextKeyName": "page-first-text", "PageTextValueName": "Lorem ipsum dolor sit amet" }, { "PageTextKeyId": 2, "PageTextKeyName": "after-page-first-text", "PageTextValueNa ...

"Create a React button component that, when clicked, navig

I'm currently developing a web application using React and bootstrap. I'm facing difficulties in redirecting the page to another one when applying onClick to buttons. After adding a href, I'm unable to navigate to another page. Do you think ...

Error occurs when attempting to instantiate a class with parameters that do not match any available constructor signatures

I am attempting to encapsulate each instance of router.navigateByUrl within a class function, with the intention of calling that function in the appropriate context. However, I am encountering an error that states 'Supplied parameters do not match any ...

When the browser back button is clicked, conceal the current div and reveal the previously hidden div

I'm faced with a situation where my website consists of multiple pages which I've achieved by displaying and hiding divs within a single html file. The issue I'm encountering is that the browser's back and forward buttons aren't fu ...

Issue with Express.js res.append function: Headers cannot be set after they have already been sent

I encountered an issue in my express project where I tried to set multiple cookies using "res.append" in the same request, but I kept getting an error saying "Error: Can't set headers after they are sent.". Can someone help me identify the problem and ...

Using JavaScript with namespaces in C#

I am currently trying to explore AJAX and web services through self-teaching using C# and JavaScript. After doing some research on Google, it seems like I might be facing a namespace problem. Here is the snippet of my code: using System; using System.Col ...

The issue of the DNN ModuleID not being effectively communicated from the code behind to the ascx component is

Background: I am utilizing a DNN (DotNetNuke) content management system to support VB.NET/Angular1 modules. Currently, I am facing an issue where a value in the code-behind is not accessible in the View.ascx of my module, resulting in a critical runtime e ...

Why does Socket.IO seem to be registering two clients instead of just one when there is only one connection

When using my app, the user first lands on the home screen where they can select their username. They then proceed to another page and from there, navigate to the room entry page. The issue I'm facing is with a specific section of my code that update ...

What is the best way to simulate an external class using jest?

My Vue page code looks like this: <template> // Button that triggers the submit method </template> <script> import { moveTo } from '@/lib/utils'; export default { components: { }, data() { }, methods: { async ...

Array contains a copy of an object

The outcome I am striving for is: dataset: [ dataset: [ { seriesname: "", data: [ { value: "123", }, { value: &q ...

The scrolling behavior varies in Firefox when using the mouse wheel

Currently, I am working on a website where I want to display large text on the screen and have the ability to scroll two divs simultaneously. This functionality is already in place. I can scroll the divs, but I'm facing an issue with the jumps being t ...

Having trouble signing out in Nextjs?

As a newcomer to Reactjs and Nextjs, I am currently working on developing an admin panel. To handle the login functionality, I have implemented the following code in my index.js/login page using session storage: const data = { name: email, password: pa ...