如何在 Ionic 5 中自行关闭模态

How self dismiss a modal in Ionic 5

我有一个打开模态的组件执行一些异步操作,我想在异步函数即 fetchData 解析后自行关闭模态。

@Component({
})
export class MyComponent implements OnInit { 
  openModal() {
   const modal = await this.modalCtrl.create({
      component: MyModalComponent,
   });
   await modal.present();
  }
}

@Component({
})
export class MyModalComponent implements OnInit { 
  fetchData() {
    this.fetchData().subscribe((response) => {
       // do some stuff

       // Dismiss the modal here
    })
  }
}

首先,您必须创建一个通用服务来包装模态功能,同时还要确保您保持状态,即哪个模态正在 return 正在处理哪些数据(以防您在彼此之上打开多个模态).

async showModal(modalPage, fullscreen: boolean, componentProps?) {
let resolveFunction: (res: any) => void;
const promise = new Promise<any>(resolve => {
  resolveFunction = resolve;
});
const modal = await this.modalCtrl.create({
  component: modalPage,
  cssClass: fullscreen ? 'full-screen-modal' : 'half-screen-modal',
  componentProps
});

modal.onDidDismiss().then(res => {
  resolveFunction(res);
});
await modal.present();
return promise;

}

那么你把模态页面做成如下:

import { Component, OnInit } from '@angular/core';
import { DisplayService } from 'src/app/services/display/display.service';

@Component({
  selector: 'app-rating',
  templateUrl: './my-modal.page.html',
  styleUrls: ['./my-modal.page.scss'],
})
export class MyModal implements OnInit {

  constructor(private displayService: DisplayService) {}

  ngOnInit() {
  }

  sendValue() {
    // do whatever async task you need to do here then close modal when finished
    this.displayService.closeModal({...returnData}); // Optionally pass return Data here if you need it in the calling page
  }

}

最后,您的父页面应该如下所示,以显示您的模式并对 return 数据采取行动:

async openModal(){
    await this.displayService.showModal(MyModal, false, null).then( res => {
      // wait for the modal to return data when it exits
      if (res.data.value1){
        const payload = {rating: res.data.value1, remarks: res.data.value2};
        // make API call 
        this.displayService.showToast(`Thank you`, 'success');
      }else {
        this.router.navigate([`failed-route-view/`]);
      }
    });
  }

一个更简单的方法是在函数 fetchdata() 中放入 Modal dismiss 函数。举个例子:

  fetchData() {
    this.fetchData().subscribe((response) => {
       // do some stuff

       // Dismiss the modal here
       this.modalController.dismiss(); 
    })
  }

您也可以使用条件 (if) 来检查响应数据,如果它已经有值,请在关闭模态之前检查是否打开了模态。干得好!

export class MyModalComponent implements OnInit {
 fetchData() {
  this.fetchData().subscribe((response) => {
   // do some stuff
     this.modalCtrl.dismiss()
   // Dismiss the modal here
   })
 }}