我有一個打開模式的組件執行一些異步操作,我想在異步函式即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
})
}
}
uj5u.com熱心網友回復:
首先,您必須創建一個通用服務來包裝模態功能,同時確保您保持哪個模態回傳哪些資料的狀態(以防您打開多個模態在另一個之上)。
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
}
}
最后,您的父頁面應如下所示,以顯示您的模式并對回傳資料采取行動:
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/`]);
}
});
}
uj5u.com熱心網友回復:
一個更簡單的方法是在你的函式 fetchdata() 中放入 Modal 關閉函式。跟隨一個例子:
fetchData() {
this.fetchData().subscribe((response) => {
// do some stuff
// Dismiss the modal here
this.modalController.dismiss(); ????
})
}
您也可以使用條件 (if) 來檢查回應資料,如果它已經有值,或者在關閉模態之前檢查是否打開了模態。做得好!
uj5u.com熱心網友回復:
export class MyModalComponent implements OnInit {
fetchData() {
this.fetchData().subscribe((response) => {
// do some stuff
this.modalCtrl.dismiss()
// Dismiss the modal here
})
}}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/460329.html
標籤:javascript 有角度的 打字稿 离子框架
上一篇:物件鍵值為空但有資料
