[英]Ionic Modal not passing data back
問題是從模態返回的數據未定義我用來打開模態的 function 如下:
async openResultsModal() {
this.ResultsPopover = await this.modalController.create({
component: ResultsPage,
componentProps: {
gameMode: this.gameMode,
Localresult: this.LocalGameResult
},
mode: "ios"
});
this.ResultsPopover.onDidDismiss().then((dataReturned) => {
if (dataReturned !== null) {
console.log(dataReturned.data);
}
});
return await this.ResultsPopover.present();
}
但是,這個 function 位於服務文件中,我在計時器中調用它,如下所示:計時器將需要保持
setTimeout(() =>
{
this.openResultsModal();
},
1500);
我的模態頁面是這樣的:
export class ResultsPage implements OnInit {
gameMode;
Localresult;
constructor(navParams: NavParams, public modalController: ModalController) {
this.gameMode = navParams.get('gameMode');
this.Localresult = navParams.get('Localresult');
}
ngOnInit() {
}
ionViewWillLeave(){
this.closeModal();
}
async closeModal() {
const onClosedData: string = "This is Data";
await this.modalController.dismiss(onClosedData);
}
}
返回到我的服務文件的數據未定義。 是因為我使用的是 JavaScript setTimeout() function?
我不認為使用 setTimeout 會導致這個問題。 讓我們找出答案,試試下面的代碼,這對我來說是有效的。
this.modalCtrl.create({
component: ResultsPage,
// backdropDismiss: false, // uncomment to prevent dismiss the modal via backdrop click
componentProps: {
gameMode: this.gameMode,
Localresult: this.LocalGameResult
}
}).then((resultPageModal) => {
resultPageModal.present().then((x) => {
console.log('Modal was presented');
});
return resultPageModal.onDidDismiss();
}).then((result) => {
console.log('Captured Data', result.data);
})
如果這可行,那么問題與您的鏈中的一個 Promise 有關。
編輯1:
問題似乎與您關閉模式的方式有關。 據我所知,如果通過背景點擊關閉模式,您將無法將數據傳回(我將對此進行更多調查並相應地更新答案)所以
ionViewWillLeave(){
this.closeModal();
}
不管用。
相反,您應該向模式的關閉按鈕(或任何其他按鈕)添加一個單擊偵聽器,並在模式創建期間設置 backgroundDismiss: false
<ion-header>
<ion-toolbar>
<ion-title>My Modal Title</ion-title>
<ion-buttons slot="primary">
<ion-button (click)="onDismiss()">
<ion-icon name="close" slot="icon-only"></ion-icon>
</ion-button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content class="ion-padding ion-text-center">
<h1>This is the content of the Modal</h1>
<ion-button (click)="onSaveData()">Save Data!</ion-button>
</ion-content>
You.ts 文件應如下所示
export class ResultsPage implements OnInit {
@Input() gameMode: GameMode; // Use the right type here
@Input() Localresult: Result; // Use the right type here
constructor(private modalCtrl: ModalController) {
}
ngOnInit() {
}
onSaveData() {
this.modalCtrl.dismiss({message: 'It works'}, 'accept').then();
}
onDismiss() {
this.modalCtrl.dismiss(null, 'cancel').then();
}
}
最后的建議,您可能不必使用 NavParams。 如果您在 Modal 組件中將這些 props 定義為 @Input(),Ionic 的 ModalController 將自動為您設置 componentProps
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.