我正在尝试创建一个包装器服务 LoaderService 在Ionic4之上 LoadingController
LoaderService
LoadingController
这是我的代码片段
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调用时显示和关闭加载器。
问题:当我使用我的 装载机服务 在我的组件中,我得到了 TypeError: Cannot read property 'present' of undefined . showLoader 在异步创建加载程序之前调用。
装载机服务
TypeError: Cannot read property 'present' of undefined
showLoader
下面是我的组件在进行API调用和调用loader时的代码:
getTopHeadlines() { this._loaderService.showLoader(); this._newsApiServcie.getTopHeadLines('in') .subscribe(res => { this.articleList = res.articles; this._loaderService.hideLoader(); }); }
另外,请查看浏览器控制台
因为加载控制器会在解散时被销毁,所以即使您的意图很高尚(在内存中有一个加载程序覆盖,然后显示/隐藏它),这种方法似乎并不理想。
动态创建加载程序覆盖并没有什么害处。我会将您的代码修改为如下所示:
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; } }