我正在使用 Ionic/Angular 進行編碼。
我想將一個函式作為引數傳遞給另一個檔案中的函式,但該函式沒有被呼叫。
警報服務.ts
showAlertWithAction(header: string, message: string, action: () => void) {
const alert = this.alertController.create({
cssClass: 'custom-alert-ok',
backdropDismiss: false,
message,
header,
buttons: [{
text: 'Okay',
handler: () => action()
}]
});
alert.then(createdAlert => createdAlert.present());
}
該函式在另一個檔案中被呼叫:
一些.page.ts
this.alertService.showAlertWithAction("Hello!", "Press Okay to close the modal", () => { this.closeModal() })
async closeModal() {
await this.modalController.dismiss()
}
uj5u.com熱心網友回復:
需要檢查的幾件事:
closeModal()真的需要嗎async?我想這會this.modalController.dismiss()回傳一個承諾,但是您似乎不需要該承諾的回傳值(即 no.then())中的任何內容,因此您的函式可能看起來像這樣并且仍然關閉您的模態:closeModal(): void { this.modalController.dismiss() }如果實作了第 1 點,則
closeModal成為 shape 的函式() => void。這與您想傳遞給您的action論點的形狀相同。正確的方法是this.alertService.showAlertWithAction( "Hello!", "Press Okay to close the modal", this.closeModal // Note: Do not include the brackets, this is now a function reference )如果您想將一個函式從一個檔案傳遞到另一個檔案,通常您希望“使用原始檔案中的所有資料”執行該函式。換句話說,您想保留該功能“執行背景關系”。
例如,
this.modalController可能是被傳遞到some.page.ts. 當你傳入closeModal()另一??個檔案時,你真正想說的是“呼叫我有權訪問.dismiss()的實體。modalControllersome.page.tssome.page.ts在這種情況下,我們希望在傳遞之前將系結的執行背景關系附加到我們的方法:this.alertService.showAlertWithAction( "Hello!", "Press Okay to close the modal", this.closeModal.bind(this) )
假設警報組件中的所有邏輯都正確呼叫handler按鈕上的方法,現在應該觸發傳入的方法
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/432950.html
