Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
    });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading