Here is the code where I use delete confirmation I want to add Error Handeling if it not delete the data then I can handel the error
confirmPopUp(){
Swal.fire({
title: 'Are You Sure?',
text: 'Deleting Service Team Detail',
icon: 'warning',
showCancelButton: true,
confirmButtonText:('Yes, delete it'),
cancelButtonText: 'No, Keep it'
}).then((result) => {
if(result.value){
this.deleteServiceTeamById(40);
Swal.fire(
'Deleted!',
'Your imaginary File has been Deleted',
'success'
)
} else if (result.dismiss === Swal.DismissReason.cancel){
}
})
}
I want to add the solution similiar like that but Unable to understand how to add this in my code
Example:
that.http.get(url, {"headers": headers})
.map(res => res)
.subscribe(data => {
console.log(data);
if (data.status === 200) {
resolve();
} else {
reject(data.status);
}
})
})
Both are Async tasks, means they should wait for the task to execute any code after that,
there are several ways to handle this, but one of the easiest i can suggest is this one (with modifications i made): Important: i will make this suggestion basing on the given chunks of code, this does not mean this is the only solution.
Http request logic (basing on promises):
/**
* the Http delete request to the API
*
*/
deleteHttpRequest(url, headers){
return new Promise((resolve,reject) => {
this.http.get(url, {"headers": headers})
.map(res => res) // .map in this case has no sense you can remove it
.subscribe(
data => {
console.log(data);
if (data.status === 200) {
resolve();
} else {
reject(data.status);
}
},
serverError => {
reject(serverError.error); // basing on HttpResponseError
}
);
});
}
}
Confirm popup
/**
* Confirm before delete
*/
confirmPopUp(confirmCallBack, cancelCallback){
Swal.fire({
title: 'Are You Sure?',
text: 'Deleting Service Team Detail',
icon: 'warning',
showCancelButton: true,
confirmButtonText:('Yes, delete it'),
cancelButtonText: 'No, Keep it'
}).then((result) => {
if(result.value){
confirmCallBack(); // <======= Here we will execute Http request
} else if (result.dismiss === Swal.DismissReason.cancel){
cancelCallback(); // <======== Here you can do whatever you want after canceling your delete action.
}
})
}
Put all in one:
/**
* Call popup confirmation then execute logic basing on confirmation status (confirm : execute http Request, cancel: do whatever you want)
*/
executeHttpAndGetResult() {
this.confirmPopUp(
() => { // when confirmed we will call deleteHttpRequest (confirmCallBack)
this.deleteHttpRequest(url, headers)
.then(
res => { // when delete successed
Swal.fire('Deleted!','Your imaginary File has been Deleted', 'success');
.catch( // catch will be called whenever data.status !== 200 or there is a server Error returned.
error => {
// display an error popup or whatever
}
);
},
// when confirmation was canceled what we will do (cancelCallback)
() => {
// @todo
}
);
}