Currently, I am facing an issue with TypeScript where I need to call a Modal within a function. The problem arises when a service is called to validate certain data from the server asynchronously. Depending on the response received from the server, I want to either open the modal or skip it entirely. However, due to the asynchronous nature of the server call, the modal ends up opening before the response is received. Is there a way to ensure that the server response is processed first, and then decide whether to open the modal?
For example, in the code snippet below: The CheckandOpenModal
function should wait for the completion of the saveRecord
method and based on its return value, decide whether to open the modal. Currently, because the control returns to the calling function before receiving the server response, the output remains at 0 and the modal gets triggered.
Any insights on how to tackle this issue would be greatly appreciated.
Here is the main function:
public output:number = 0;
CheckandOpenModal() {
/* do something */
this.saveRecord(); // Need to await for this to finish and retrieve output
if (this.output == 0) {
// Open the modal window
const modalRef = this.modalService.open(editTableColComponent, {
centered: true,
scrollable: true
});
} else {
// Perform other actions
}
}
saveRecord() {
this.serv.checkTableRecord(this.objTableFields.tableNm, this.objTableFields.tableID).subscribe(data => {
if (data.check.result == 1) {
this.output = 1;
}
});