Using Angular UI Router with $ionicLoading for Resolving Tasks

Is there a way to incorporate $ionicLoading with Angular's UI Router resolves? The goal is to display a loading modal when a new route/state is requested and have it disappear once the data is resolved and the new state is loaded.

router

.state('tab.locations', {
  url: '/locations',
  cache: false,
  views: {
    'locations-tab': {
      templateUrl: 'js/locations/tab-locations.html',
      controller: 'LocationsCtrl as vm'
    }
  },
  resolve: {
    locationsResource: 'Locations',
    locations: function(locationsResource) {
      return locationsResource.all();
    }
  }
})

If resolves are not used, one approach is to utilize $httpProvider.interceptors to trigger events for showing and hiding the loading screen. For example:

$ionicConfigProvider

$httpProvider.interceptors.push(function($rootScope) {
  return {
    request: function(config) {
      $rootScope.$broadcast('loading:show');
      return config
    },
    response: function(response) {
      $rootScope.$broadcast('loading:hide');
      return response
    }
  }
})

runBlock

$rootScope.$on('loading:show', function() {
  $ionicLoading.show({template: '<ion-spinner></ion-spinner>'})
});

$rootScope.$on('loading:hide', function() {
  $ionicLoading.hide()
});

This setup works well without resolves. However, when using resolves, the loading screen does not appear.

Attempts were made to broadcast loading:show on $stateChangeStart if a resolve is present, but that did not solve the issue.

Are there other interceptors or state change events that should be utilized to trigger loading:show and loading:hide in order to make $ionicLoading work seamlessly with resolves?

Answer №1

After encountering a similar issue, I came across a solution that worked for me:

$rootScope.$on('loading:show', function () {
    $ionicLoading.show({
        template:'Please wait..'
    })
});

$rootScope.$on('loading:hide', function () {
    $ionicLoading.hide();
});

$rootScope.$on('$stateChangeStart', function () {
    console.log('please wait...');
    $rootScope.$broadcast('loading:show');
});

$rootScope.$on('$stateChangeSuccess', function () {
    console.log('done');
    $rootScope.$broadcast('loading:hide');
});

This useful tip was shared on the Ionic forum here

Answer №2

I also faced a similar issue. While simple HTTP requests worked fine, using state resolve posed challenges.
One solution is to employ a basic module that can intercept all $http requests effectively.
https://github.com/chieffancypants/angular-loading-bar
This module generates events that can be utilized with $rootScope.$on.

The event cfpLoadingBar:started is triggered initially upon the first XHR request. It will trigger again if another request occurs after cfpLoadingBar:completed has been triggered.

The event cfpLoadingBar:completed fires once all XHR requests have completed (regardless of success or failure).

This information could be helpful for those still struggling with this issue :)

Answer №3

This is my approach to solving the issue in my current app:

export var ngModule = angular.module('myApp', ['ionic']);

ngModule.run(($ionicPlatform: ionic.platform.IonicPlatformService, $state: ng.ui.IStateService, $rootScope: ng.IRootScopeService, $ionicLoading: ionic.loading.IonicLoadingService) => {
    $ionicPlatform.ready(function () {

        if (window.cordova && window.cordova.plugins.Keyboard) {
            cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
            cordova.plugins.Keyboard.disableScroll(true);
        }
        if (window.StatusBar) {
            StatusBar.styleDefault();
        }
        $rootScope.$on("$stateChangeStart", (event, toState, toParams, fromState, fromParams) => {
            $ionicLoading.show({
                delay: 200,
                template: "Loading..."
            });
        });

        $rootScope.$on("$stateChangeSuccess", (event, toState: ng.ui.IState, toParams, fromState, fromParams) => {
            $ionicLoading.hide();
        });

        $rootScope.$on("$stateChangeError", (event, toState, toParams, fromState, fromParams, error) => {
            $ionicLoading.hide();
            console.error("An error occurred while loading the page: %o", error);
        });
        $state.go("login");
    });
});

While this code is written in TypeScript, it can be easily translated into JavaScript.

In fact, there is no need for http interceptors or broadcasting angular events with this solution.

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

The process of transferring a local image file to the Clarifai API

I am currently exploring the functionality of the food categorization API provided by clarifai. However, I noticed that the example in the documentation uses a publicly hosted image. Is there a way for me to utilize the API with an image from a local direc ...

When attempting to utilize putImageData on the HTML5 canvas context, an error occurs stating that the overload resolution has failed

While following the MDN canvas tutorial, I encountered an issue with a code snippet I wrote. The code is supposed to color the top left corner (50x50 pixels) of the canvas in red. However, I'm receiving an error message that says Overload resolution ...

Looking for a JavaScript snippet to insert the word "Search" into an empty DIV element with the specified id attribute

I am trying to insert the word "Search" into an empty input field with the id "ReportQuery" using JavaScript. Unfortunately, I do not have access to the HTML code directly. How can I achieve this task through coding? Below is the snippet of code that nee ...

Awesome method of redirecting outdated URLs to the most recent established URL

My website heavily relies on JavaScript and communicates with a .NET C# RPC service. We encountered an issue where clients' browsers cached the JavaScript, so we decided to add a version number to the URL in order to force them to use the latest JavaS ...

What is the method to find the biggest number in an array?

I'm encountering challenges with this piece of code and it seems impossible to locate a resolution. Take a look at the code snippet: function findHighestValue(numbers) {} const highestValue = findHighestValue([1, 9, 5]); console.log(highestValue); ...

angularjs instructions for modifying each text value individually

How can I modify the label value for each appended field when clicking on the field? Visit this link to view the code in a plunkr. var app = angular.module('myapp', ['ngSanitize']); app.controller('AddCtrl', function ($sco ...

Integrating Illumination into a ShaderMaterial in three.js

I'm exploring the idea of creating a ShaderMaterial with lighting similar to that of a MeshLambertMaterial. To achieve this, I have developed a vertex and fragment shader (available here) and included the uniforms from THREE.ShaderLib[ 'lambert&a ...

The functionality of reordering columns, virtual scrolling, and resizing the grid in jqgrid are not functioning properly

Implementing jqgrid with Symfony to display a datagrid has been a challenging task for me. Thanks to Oleg's insightful response, many of the major issues have been resolved. Below is a snippet of my code: <link rel="stylesheet" type="text/css" ...

Trouble with NodeJS NPM

I'm encountering difficulty when trying to install npm packages. npm ERR! Windows_NT 6.3.9600 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules&bso ...

Adjust parameters using JavaScript and three.js in real-time

I am not well-versed in JavaScript and I am facing an issue. I need to dynamically change the parameter passed to a function written in JavaScript, but the code is structured in a way that is unfamiliar to me. Therefore, I am seeking assistance. On my web ...

Utilize a display value while maintaining the v-model binding in Vue.js

Can't seem to figure this one out. I'm using Quasar Framework, but it seems like more of a Vue issue. I have a multiple-select UI component with a list of objects as options that I want to display. The v-model will bind to the currently selected ...

Error in breeze query, despite successful retrieval of results

Despite data being returned from the odata service and present in the error object, Breeze is triggering the "fail()" function. In both Chrome developer tools and the "data" property of the error object, there are 5 "transactions" retrieved from the ODATA ...

Styling sub-table titles in jQuery jTable with proper indentation

I am currently implementing jquery.jtable, where I have rows that invoke the openChildTable method in the jquery.jtable.js file. I'm attempting to figure out a way to indent the heading of the child table. Below is the code snippet responsible for cr ...

What is the best way to display a new line when printing a string as <pre> in HTML without using ` `

I receive a text file from the PHP server that has the following content: "File version: 5\n\nstart: 1410355285955(2014/09/10 11:58:05.955)\nend: 141090402750(2014/09/10 12:00:02.750)\nUEID: 301660031\nCNC: 1181 ...

Refresh the page to view multiple modals in one window on W3

I've been attempting to repurpose the W3 image modal code in order to open multiple modals on the same page. I managed to come up with a solution based on answers I found here, but unfortunately, it only seems to work if I refresh the browser page (si ...

The CanJS model is unable to retrieve data from a .json file

Implementing MVC using AMD in canjs with requirejs has been my current focus. Here's a look at my domains.json file: [ "1":{"uid": "1","urls": "domain1.abc.com"}, "2":{"uid": "2","urls": "domain2.abc.com"}, "3":{"uid": "3","urls ...

Accessing instance variables from a chained observable function in Angular 2/Typescript

Currently, I am utilizing Angular2 along with Typescript. Let's assume that there is a dummy login component and an authentication service responsible for token authentication. In one of the map functions, I intend to set the variable authenticated as ...

Unraveling based on changing values in es6

Trying to retrieve query parameters from the frontend in my express endpoint. const { filterType1, filterType2 } = req.query However, the issue is that the filterType values are coming from a predefined list of array elements. const list = ['priceF ...

Implementing Oauth in Angular and Node

I am facing challenges with implementing oauth in Angular. When I directly enter the link into the browser http://localhost:8080/auth/twitter I am able to successfully connect using oauth and receive a response. However, when I try to achieve the same in ...

JavaScript Geocoding does not initiate the search process

Currently in the process of moving some Google Maps functions to a separate file. In my main file, I have a function search() that sets up a workflow with the other file included. The issue I'm facing is with the geocoder.geocode() function, which was ...