首页 > 解决方案 > Ionic 4:“加载控制器”dismiss() 在 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();
}

标签: angularionic-frameworkangular6loadingionic4

解决方案


这就是我解决问题的方法..

当调用dismiss() 时,我使用布尔变量“isLoading”更改为false。在 present() 完成后,如果 "isLoading" === false (表示dismiss() 已经调用),那么它将立即关闭。

另外,我在服务中编写了代码,因此不必在每个页面中再次编写代码。

加载.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'));
  }
}

然后只需从页面调用 present() 和 dismiss() 即可。

有问题的例子:

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

推荐阅读