带有angular7的Ionic 4:创建加载程序服务时出现问题(异步/等待)

时间:2019-01-05 14:25:59

标签: javascript angular ionic-framework async-await ionic4

我正在尝试在Ionic4 LoaderService之上创建包装服务LoadingController

这是我的LoaderService的代码段

export class LoaderService {

    loader: HTMLIonLoadingElement;

    constructor(public loadingController: LoadingController) {
        console.log('constructor called');
        this.createLoader();
    }

    async createLoader() {
        this.loader = await this.loadingController.create({
            message: 'Loading',
        });
        console.log('loader created');
    }

    async showLoader() {
        await this.loader.present();
    }

    hideLoader() {
        this.loader.dismiss();
    }

}
  

要实现的目标:使用服务,我想在我的应用中创建一个加载器实例,并允许组件在进行API调用时显示和关闭该加载器。

问题:当我在组件中使用LoaderService时,我得到了TypeError: Cannot read property 'present' of undefined。 发生这种情况是因为在异步创建加载程序之前调用了showLoader

这是我进行API调用和调用加载程序时的组件代码:

getTopHeadlines() {
    this._loaderService.showLoader();
    this._newsApiServcie.getTopHeadLines('in')
        .subscribe(res => {
            this.articleList = res.articles;
            this._loaderService.hideLoader();
        });
}

还要看一下浏览器控制台 enter image description here

1 个答案:

答案 0 :(得分:0)

由于加载控制器在解雇时被破坏,因此即使您的意图是高尚的(在内存中覆盖一个加载器,然后显示/隐藏它)-这种方法似乎不是最优的。

动态创建加载程序覆盖图没有任何危害。我将您的代码修改为如下所示:

加载程序服务

export class LoaderService {

    loader: HTMLIonLoadingElement;

    constructor(public loadingController: LoadingController) {
    }

    showLoader() {
        if (this.loader) { 
            this.loader.present()
        } else {
            this.loader = this.loadingController.create({
                message: 'Loading',
            }).then(() => {
                this.loader.present()
            })
        }
    }

    hideLoader() {
        this.loader.dismiss();
        this.loader = null;
    }

}