Display the Ionic loading spinner until the data is fully loaded

Currently, I am developing an application using the Ionic framework. My goal is to display a loading spinner until all the data is retrieved from an API.

In the Controller.js file:

.controller('PrayersCtrl', function($scope, Prayers, $ionicLoading, $timeout) {
                $ionicLoading.show({
                content: 'Loading',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
              });

        $scope.prayers = Prayers.query();
        $ionicLoading.hide();

    })

And in the Services.js file:

angular.module('starter.services', [])

.factory('Prayers', function($resource) {
    return $resource(base_url+'/wp/v2/posts');
});

The issue I'm facing is that the spinning wheel doesn't show up properly; it appears and disappears very quickly, then there's a delay in loading the data. During this time, a blank page is displayed until the data is loaded. My objective is to keep showing the spinning wheel until the data is fully loaded on the page.

Updated Approach

I also attempted to use a timeout function in the controller.js:

.controller('PrayersCtrl', function($scope, $stateParams, Prayers, $ionicLoading, $timeout) {
      $ionicLoading.show({
        content: 'Loading',
        animation: 'fade-in',
        showBackdrop: true,
        maxWidth: 200,
        showDelay: 0
      });
      $timeout(function () {
        $ionicLoading.hide();
        $scope.prayers = Prayers.query();
      }, 2000);
    })

However, with this approach, the spinning wheel disappears after 2000 ms according to the code. What I truly want is for the spinning wheel to continue displaying until all the data is completely loaded.

Answer №1

After updating controller.js, I included a $promise following the query function along with modifications to handle network errors and display appropriate messages.

.controller('PrayersCtrl', function($scope, Prayers, $ionicLoading, $timeout) {
    $ionicLoading.show({
        content: 'Loading',
        animation: 'fade-in',
        showBackdrop: true,
        maxWidth: 200,
        showDelay: 0
    });

    $scope.prayers = Prayers.query().$promise.then(function(result) {
        console.log(result);
        $scope.prayers = result;
        $ionicLoading.hide();
    }, function(error) {
        console.log(error);
        $ionicLoading.hide();
        $ionicLoading.show({
            template: 'Network Error',
            scope: $scope
        });
        $timeout(function() {
            $ionicLoading.hide();
        }, 2000);
    })
})

I also reverted the services back to their original form.

angular.module('starter.services', [])

.factory('Prayers', function($resource) {
    return $resource(base_url+'/wp/v2/posts');
});

Answer №2

Hey Muhammad, I made a few adjustments to your solution in order to tailor it to my needs. Take a look at my modified controller below.

.controller('PrayersCtrl', function($scope, $ionicLoading, Prayers, $timeout) {
  $ionicLoading.show({
    template: '<ion-spinner icon="spiral" class="spinner-positive"></ion-spinner> <br>Loading...',
    noBackdrop: true,
    animation: 'fade-in'
  });
  Prayers.query().$promise.then(function(result){
    $scope.prayers = result;
    $ionicLoading.hide();
  }, function(error) {
    // error handling here
    $ionicLoading.hide();
    $ionicLoading.show({
      template: "unable to connect",
      noBackdrop: true
    });
    $timeout(function() {
       $ionicLoading.hide();
    }, 2000);
  })
})

Answer №3

Here is a suggested solution to try:

.controller('RecipesCtrl', function($scope, Recipes, $ionicLoading, $timeout) {
                $ionicLoading.show({
                content: 'Loading',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
              });

        $scope.recipes = Recipes.query().then(function(result){
         console.log(result);
         $ionicLoading.hide();
        }, function(error){
         console.log(error);
          $ionicLoading.hide();
        })          
    })


Make sure to update the code in your factory as follows:

angular.module('app.services', [])

.factory('Recipes', function($resource, $q) {
  var self = this;
  self.query = function(){
  var defer = $q.defer();
   $resource(base_url+'/api/v1/recipes').then(function(result){
   console.log(result);
   defer.resolve("success");
   }, function(error){
   console.log(error);
   defer.reject("error");
  })
   return defer.promise;
  }
  return self;


});

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

Verifying the existing user in a personalized Ajax form that is used to update a Woocommerce order

Currently, I am developing a form that allows users to update specific order details, such as expenses and the reason for the expense. After updating the order, a JavaScript alert confirms the successful update, and the order's metadata is updated acc ...

How to dynamically add variables to object paths using JavaScript and Angular

I've been struggling to grasp this concept, despite hours of searching. My goal is to dynamically generate form fields based on a user-selected 'type' from a dropdown menu. This will be linked to the variable "currentType" in Angular, which ...

Click the JavaScript button to activate the delete function

Imagine an interactive HTML table where a user can easily delete rows by either selecting a row and pressing the delete key on their keyboard or by clicking a designated delete button. This functionality ensures a smooth and intuitive user experience. Se ...

The animation does not reoccur in Firefox when using Modal

I have a unique issue with my modal that displays images, where the animation only works the first time on Firefox. When I open the modal for the first time, everything works perfectly, but if I close it and then reopen it, the animation no longer plays. I ...

The functionality of the Bootstrap 4 Carousel featuring multiple items is experiencing malfunctions

I'm encountering an issue with my Bootstrap 4 card carousel. When the next or prev buttons are clicked, there is a strange transition effect. Additionally, in the mobile version, the buttons do not work properly. It seems that when the card slides to ...

Updating of an Angular Directive within a nested Directive ceases once the inner Directive has been modified

Encountered a challenge with directives nested within each other in AngularJS. The issue is that both directives share the same property through a service and have an input to modify this property. The outer directive uses "transclude" to include the inner ...

using ng-show to display array elements

There is a syntax error showing up on the console for the code below, but it still functions as intended. Can someone help identify what I might be missing? <p class="light" data-ng-show="selectedAppType in ['A1','A2','A3' ...

Eliminate a row in an HTML table depending on a certain condition

I have an HTML table that I am dynamically adding values to: <TABLE id="dlStdFeature" Width="300" Runat="server" CellSpacing="0" CellPadding="0"> <TR> <TD id="stdfeaturetd" vAlign="top" width="350" runat="server"></TD> < ...

What methods can be used to differentiate between value equality and reference equality when watching something?

In the world of AngularJS, the $watch function comes with an interesting twist - it has an optional third parameter. By default, this parameter is set to false, which means the watch will only trigger if the watched reference changes. But if you set it to ...

How to use getServerSideProps in Next.js

In my current scenario, I find myself within a folder in the pages directory, specifically in a file named [id].jsx. My goal is to make getServerSideProps return just the name of the page, for example /page/id123 should return id123. import Link from &a ...

What steps can I take to resolve my password validation rule when confirming during sign-up?

Utilizing react-hook-form in combination with Material-UI for my sign-up form has been a challenge. I am currently working on implementing a second password field to confirm and validate that the user accurately entered their password in the initial field, ...

Updating Vue.js asynchronously using JavaScript import

I am facing a challenge with two form components that share a common JS validator. import { validateInput } from './validateInput.js' export default { data () { return { email: '<a href="/cdn-cgi/l/email-protection" class="_ ...

Generate a dynamic form that automatically populates different input fields based on JSON data

I am trying to dynamically auto populate a form with various input types such as select boxes and text areas. I have successfully implemented this for input boxes, see example below: function autofill(){ var data = [{visible_retail: "0", brand: ...

Is it possible to nest Route components in react-router version 4.x?

How can one properly implement nested routes in react-router version 4.x? Previous methods like the one below worked well, but upgrading to version 4.x now results in a warning... <Route path='/stuff' component={Stuff}> <Route path=&a ...

What is the best way to add <li> to every element in an array?

I had a tough day today trying to figure out my code. My English isn't the best, so explaining my issue is hard. I decided to illustrate my problem in HTML and specify the kind of styling I need to achieve with JS. I also included an example using the ...

What is the process for obtaining a page slug within the app directory of Next.js?

How to retrieve the slug of the current page in Next.js 13, as compared to Next.js 12 where it was done in a getStaticProps method? ✅Next.js 12 export async function getStaticProps(context) { const slug = context.params.slug } ❌Next.js 13 - Using t ...

Unable to locate the tag using .find() function following the use of .attr() method

I am currently utilizing jQuery in conjunction with node-horseman to interact with a specific page. My approach involves referencing the page's data-id attribute, which I then pass to my application to search for the li element containing this attribu ...

The initial dispatch of a React hook triggers subsequent dispatches to fire multiple times

Whenever I include more than one dispatch in useEffect(), it causes all subsequent actions to be triggered twice. Please see the example below. Below is the complete code. Feel free to remove comments in any order you prefer. PS: I am not sure how to mak ...

Using jQuery to evaluate multiple conditions within an if statement

I'm working on a script that needs to continuously monitor for the presence of an input field with the class name "email" (as this content is loaded via AJAX). If this input exists, I need to show another input field with the class name of "upload". A ...

pictures in photo display

Please check out my codepen project: html code: <body> <div class="thumbnails"> <a href="#"><img src="http://s30.postimg.org/4yboplkxd/dotty.jpg" width="100" height="100"></a> <a href="#"><img src="http:// ...