Dory
Dory

Reputation: 105

How to add toaster in Angular?

Any idea how to add a toaster notification when an error occurs instead of using alert. Many tutorials out there just make a tutorial when clicking a button but I want some automatization. Below is my code

saveStudentDetails(values) {
  const studentData = {};

  studentData['id'] =  values.id;
  studentData['password'] =  values.password;
  this.crudService.loginstudent(studentData).subscribe(result => {
    this.student = result;
    this.router.navigate(['/address']);
  },
    err => {
      console.log('status code ->' + err.status);
      alert('Please try again');
 });

}

Any idea how can i make an error toaster notification base on this code? Thank you

Upvotes: 2

Views: 12585

Answers (3)

Rakesh
Rakesh

Reputation: 4252

You can use toastr. More information can be found at https://www.npmjs.com/package/toastr. The demo is at https://codeseven.github.io/toastr/demo.html

Upvotes: 0

Akil Makda
Akil Makda

Reputation: 431

For display toaster use ngx-toastr library

Steps:

1) npm install ngx-toastr --save

2) Follow other setups from here

Quick Code :

import { ToastrService } from 'ngx-toastr';

constructor(private toastr: ToastrService) {}

saveStudentDetails(values) {
  const studentData = {};

  studentData['id'] =  values.id;
  studentData['password'] =  values.password;
  this.crudService.loginstudent(studentData).subscribe(result => {
    this.student = result;
    this.router.navigate(['/address']);
  },
    err => {
      console.log('status code ->' + err.status);
      this.toastr.error('Hello world!', 'Toastr fun!');
 });

Upvotes: 5

Johan Rin
Johan Rin

Reputation: 1950

You can use any third-party toaster packages like ngx-toastr to display an error toaster notification.

For example with ngx-toastr:

constructor(
  ...
  private toastr: ToastrService
) {}

this.crudService.loginstudent(studentData).subscribe(
  result => {
    this.student = result;
    this.router.navigate(['/address']);

    this. toastr.success('Logged in');
  },
  err => {
    console.log('status code ->' + err.status);

    this. toastr.error('Please try again');
  }
);

Upvotes: 0

Related Questions