Seeking guidance on incorporating toast messages within an Angular + Ionic 6 application...
My goal is to display a toast message in response to events such as clearing a cart or submitting an order, with the message originating from an API call.
While attempting to follow the Ionic documentation for implementation, I am uncertain about how to trigger the toast message and pass it the appropriate message.
When testing using POSTMAN, the message response format appears like this:
{
"message": "You have successfully cleared the cart"
}
The API call for emptying the cart (cart.service.ts):
clearCart() {
return from(Preferences.get({key: 'TOKEN_KEY'})).pipe(
switchMap(token => {
const headers = new HttpHeaders().set('Authorization', `Bearer ${token.value}`);
return this.httpClient.delete<ShoppingCart>(`${environment.apiUrl}cart`, {headers, observe: 'response'});
}),
catchError(err => {
console.log(err.status);
if (err.status === 400) {
console.log(err.error.message);
}
if (err.status === 401) {
this.authService.logout();
this.router.navigateByUrl('/login', {replaceUrl: true});
}
return EMPTY;
}),
);
}
Below, you'll find the clearCart function along with the presentToast function taken from the Ionic documentation on my cart page (cart.page.ts):
clearCart() {
this.cartService.clearCart().subscribe(
(data: any) => {
this.products = [];
this.totalProducts = 0;
this.totalCartPrice = 0;
this.successToast(data.body.message, 'bottom');
},
error => {
console.log('Error', error);
this.errorToast(error, 'bottom');
});
}
async successToast(message, position: 'bottom') {
const toast = await this.toastController.create({
message: message,
duration: 1500,
color: 'success',
icon: 'checkmark-circle-outline',
position
});
await toast.present();
}
async errorToast(message, position: 'bottom') {
const toast = await this.toastController.create({
message: message,
duration: 1500,
color: 'danger',
icon: 'close-circle-outline',
position
});
await toast.present();
}
Am I on the right track with implementing the toast messages, or did I make a mistake early on? :)
Where should I invoke the presentToast function? How can I pass the message to it? Is creating a new toast component necessary?