How to call a toast if api call is success or error?

Issue

I need help understanding and implementing toast messages in an Angular + Ionic 6 app…

In my app I want to show a toast message upon some events like clearing a cart, submitting an order, etc… In this case I want the toast message to display the message that is sent to me via an API call.

I have tried the ionic docs implementation but I’m not sure how to call the toast message and pass it the message.

In POSTMAN the message response looks like this:

{
    "message": "You have successfully cleared the cart"
}

Here is the API call for clearing 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;
      }),
    );
  }

And here is the clearCart function with the presentToast function from the ionic docs in 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();
  }

Have I even gone on a correct path on implementing the toast messages or have I f*cked up in the beginning of it? 🙂

Where do I call the presentToast function? How do I pass the message in it? do I need to make a new toast component?

Solution

You gotta rewrite toast present method to accept message as a parameter.

async presentToast(message, position: 'bottom') {
const toast = await this.toastController.create({
  message: message,
  duration: 1500,
  position
});

And then since you’re subscribed to result form http delete request, you can
just put the toast making in clearCart() method something as:

this.cartService.clearCart().subscribe(
      (data: any) => {
        this.presentToast(data.message);
        this.products = [];
        this.totalProducts = 0;
        this.totalCartPrice = 0;
      },
      error => {
        console.log('Error', error);
    });

Answered By – chuftica

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published