moody
moody

Reputation: 402

loading animation until data is loaded in Typescript (ionic)

i would like to add an animation to the screen until the projects are loaded.

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());
    }

my first thought was to implement a settimeout which is the worstcase solution. is there a good way to solve this?

Upvotes: 0

Views: 1157

Answers (2)

BRass
BRass

Reputation: 3838

A similar alternative, using async and await.

async loadProjects() {
    // start loader:
    let loading = this.loadingCtrl.create({
        content: 'Please wait...'
    });

    try {
        await loading.present();
        this.projs = await this.network.getAllProjects();
    }
    catch (error) {
        //TODO: Log the error, show a friendly message
        this.logout();
    }
    finally {
        loading && loading.dismiss();
    }
}

Upvotes: 0

Sergey Rudenko
Sergey Rudenko

Reputation: 9227

you need to import the loader and use it accordingly to your async code:

import { LoadingController, ModalController, Platform } from "ionic-angular";
// add your further imports here...

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

loadProjects() {
        // start 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());
    }

Not sure if you posted the full code sample in your case. So I hope this will help. See usage here: https://ionicframework.com/docs/api/components/loading/LoadingController/

Upvotes: 0

Related Questions