我使用“离子加载控制器”来显示一个微调器,直到检索到数据然后它调用“dismiss()”来解除它.
它工作正常,但有时当应用程序已经拥有数据时,在“create()”和“present()”完成之前调用“dismiss()”,这将保持微调器而不会消失…
它工作正常,但有时当应用程序已经拥有数据时,在“create()”和“present()”完成之前调用“dismiss()”,这将保持微调器而不会消失…
我试图在“loadingController.present().then()”中调用数据,但这导致数据变慢…
我的代码示例:
customer: any; constructor(public loadingController: LoadingController,private customerService: CustomerService) ngOnInit() { this.presentLoading().then(a => consloe.log('presented')); this.customerService.getCustomer('1') .subscribe(customer => { this.customer = customer; this.loadingController.dismiss().then(a => console.log('dismissed')); } } async presentLoading() { const loading = await this.loadingController.create({ message: 'wait. . .',duration: 5000 }); return await loading.present(); }
解决方法
这就是我解决问题的方法..
调用dismiss()时,我使用布尔变量“isLoading”更改为false.然后在present()完成后如果isLoading === false(意味着已经调用了dismiss())那么它将立即解除.
另外,我在服务中编写了代码,所以我不必在每个页面中再次编写代码.
loading.service.ts
import { Injectable } from '@angular/core'; import { LoadingController } from '@ionic/angular'; @Injectable({ providedIn: 'root' }) export class LoadingService { isLoading = false; constructor(public loadingController: LoadingController) { } async present() { this.isLoading = true; return await this.loadingController.create({ duration: 5000,}).then(a => { a.present().then(() => { console.log('presented'); if (!this.isLoading) { a.dismiss().then(() => console.log('abort presenting')); } }); }); } async dismiss() { this.isLoading = false; return await this.loadingController.dismiss().then(() => console.log('dismissed')); } }
有问题的例子:
customer: any; constructor(public loading: LoadingService,private customerService: CustomerService) ngOnInit() { this.loading.present(); this.customerService.getCustomer('1') .subscribe( customer => { this.customer = customer; this.loading.dismiss(); },error => { console.log(error); this.loading.dismiss(); } );
注意:不要忘记将“LoadingService”添加到AppModule的提供者