加载动画,直到将数据加载到Typescript(离子)中

时间:2018-10-17 12:11:07

标签: typescript ionic-framework loading-animation

我想在屏幕上添加动画,直到加载项目。

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

我的第一个想法是实现settimeout,这是最坏的解决方案。有解决这个问题的好方法吗?

2 个答案:

答案 0 :(得分:0)

您需要导入加载程序并根据您的异步代码使用它:

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

不确定是否在您的案例中发布了完整的代码示例。所以我希望这会有所帮助。在此处查看用法:https://ionicframework.com/docs/api/components/loading/LoadingController/

答案 1 :(得分:0)

使用asyncawait的类似选择。

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