Typescript (ionic) loading animation that keeps users engaged while waiting for the data to be loaded

I'm looking to include an animation on the screen while waiting for the projects to load.

constructor(
        public platform: Platform,
        private network: NetworkService,
        public navContrl: NavController,
        public modalCtrl: ModalController
    ) {
        this.loadProjects();

        this.admin = this.network.isUserAdmin();
    }

loadProjects() {
        this.network.getAllProjects()
            .then(projects => this.projs = projects)
            .catch(err => this.logout());
    }

Initially, I considered using setTimeout as a solution, but I believe there might be a better approach. Any suggestions?

Answer №1

To successfully implement asynchronous code, make sure you import the loader and utilize it correctly:

import { LoadingController, ModalController, Platform } from "ionic-angular";
// include any additional imports here...

constructor(
    public platform: Platform,
    private network: NetworkService,
    public navContrl: NavController,
    public modalCtrl: ModalController,
    // inject the loader:
    public loadingCtrl: LoadingController
) {
    this.loadProjects();
    this.admin = this.network.isUserAdmin();
}

loadProjects() {
    // initiate the loader:
    let loading = this.loadingCtrl.create({
        content: 'Please wait...'
    });
    loading.present();
    this.network.getAllProjects()
        .then((projects) => {
            this.projs = projects;
            loading.dismiss();
         })
        .catch(err => this.logout());
}

If your code sample was incomplete, refer to the usage guide at https://ionicframework.com/docs/api/components/loading/LoadingController/ for assistance.

Answer №2

Here is an alternative approach that utilizes the async and await keywords.

async fetchProjects() {
    // Display loader:
    let loading = this.loadingCtrl.create({
        content: 'Loading projects...'
    });

    try {
        await loading.present();
        this.projectsList = await this.network.fetchAllProjects();
    }
    catch (error) {
        // Record the error and display a user-friendly message
        this.handleLogout();
    }
    finally {
        if (loading) {
            loading.dismiss();
        }
    }
}

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

"Exploring the process of retrieving URL parameters within an activated link using Angular 7 and executing a REST API call from a service

My aim is to retrieve data by utilizing the id field through Get parameters. Below is the URL code in my HTML that redirects to a specific page without triggering the service to fetch the REST API. <a [routerLink]="['/usedCars/detail', list ...

A step-by-step guide on incorporating a .env file into a React JS project that is written with TypeScript

I'm currently working on a React JS project with TypeScript. I know that we can utilize a .env file to define some configurations, like so: .env file REACT_APP_SOME_CONFIGURATION = "some value" We can then use these configurations in our c ...

Encountering an error message stating "The variable 'App' is declared but not used" when running the index.tsx function

This React project is my attempt to learn how to use a modal window. The tutorial I've been following on YouTube uses JavaScript instead of TypeScript for their React project. However, I'm facing some challenges. Could you possibly help me ident ...

Are you looking for straightforward dynamic directives that come with dynamic controllers and a scope?

Feeling like I have a simple problem to solve here. Working within the confines of a TypeScript + Angular application. Within a controller, I've got an array of similar directives that I want to utilize. These are essentially the panels strewn throug ...

Confirming changes to checkbox values in Angular 2 prior to updating

My current challenge involves implementing a confirmation dialog in my application, and I'm feeling a bit unsure about the logic behind it. UserDetailsComponent.ts import { Component, OnInit, OnDestroy, ViewChild, Input, OnChanges, SimpleChange } f ...

Error detected in Deno project's tsconfig.json file, spreading into other project files - yet code executes without issues?

I am working on a Deno project and need to utilize the ES2019 flatMap() method on an array. To do this, I have created a tsconfig.json file with the following configuration: { "compilerOptions": { "target": "es5", ...

Creating a new TypeScript file via the command line: A step-by-step guide!

When I want to create a new file named main.ts, I try to write the command but it keeps showing an error. "bash: code: command not found" https://i.stack.imgur.com/cpDy3.png ...

Using variables to replace 'placeholders' in Typescript with string interpolation

Seeking a definitive answer on this matter, I pose the question: In C#, an example of which would be as follows: var text = "blah blah"; var strTest = String.Format("This is a {0}", text); //output: 'This is a blah blah' How can I accomplish t ...

Remove the user along with all of their associated documents from Firestore

When a user wants to delete their account, I need to ensure that the 'documents' they created in Firebase are deleted as well. After some research online, I came across the following code snippet: deleteAccount() { const qry: firebase. ...

What is the best way to link multiple checkboxes to a single ng-model?

Currently, I am working on mobile app development using the Ionic framework. In order to set multiple checkboxes with the same ng-model, I want all three checkboxes to be clicked when one is selected. However, the values are not being stored as expected. ...

How can I display 4 react components, such as custom buttons, in a manner that ensures the most recently pressed button appears on top?

I've been attempting to solve this problem, but I'm struggling to find a solution. My current approach involves grouping the 4 button components in an array and shifting their positions based on user input. Is there a more efficient way to accomp ...

Utilizing Regular Expressions as a Key for Object Mapping

Currently, I am facing a challenge in mapping objects with keys for easy retrieval. The issue arises when the key can either be a string or a RegExp. Assigning a string as a key is simple, but setting a regex as a key poses a problem. This is how I typica ...

The 'length' property is not found within the 'HTMLElement' type

Can someone assist me with looping over the number of nav-items I have? I am encountering an error that says: Property 'length' does not exist on type 'HTMLElement'. I understand that changing document.getElementById('nav-item) to ...

Error in angular2-color-picker module: Unable to retrieve the property 'substr' from an undefined source-node in source-node.js

Error in angular2-color-picker: Issue with 'substr' property, source-node.js This error occurred when I executed: npm i --save angular2-color-picker Any suggestions on how to fix this problem? ...

What is the reason behind the triggering of actions by ngrx entity selectors?

I'm currently in the process of learning NgRx, but I'm struggling to comprehend why entity selectors would trigger actions. Despite my efforts to find an explanation, I have come up short. It's possible that I may be missing some fundamental ...

Tips for customizing components in React-Table by overriding default columns

In a nutshell, I was tasked with developing a table component using react-table. By default, the table uses an input component that allows instant typing when double-clicked. Additionally, I wanted one of the columns in editableCell to use a dropdown. I ...

Transforming a few lines of PHP header code to Classic ASP

I am encountering an issue with two files that I have: A locally hosted project coded in Ionic/AngularJS that is attempting to retrieve JSON data from an ASP file. An external ASP File which generates JSON data based on database values from a query. Eve ...

Which is more efficient for optimizing code: Typescript compiler or ES2015?

When it comes to compiler optimization in other programming languages, a similar scenario would involve pulling out certain objects from the loop to avoid creating them each time: const arr = [1, 2, 3, 4, 5] arr.map(num => { const one_time = 5; / ...

Exploring the Power of Chained Promise Calls

Afterwards, in the .then section, I call another promise for an HTTP request: .then(result => { this.service().then(data => {}); }); Would you say that using chained promises in this manner is correct? ...

The module '@/assets/icons/pay/pay-success.png' cannot be located, along with its corresponding type declarations.ts

Recently, I encountered an issue while trying to import a png image in my Typescript code. Here is the snippet of code that caused the error: import paySuccessIcon from "@/assets/icons/pay/pay-success.png"; When I tried to import the image, Visual Studio ...