angularangular-toastr

Toaster is not triggering in angular4


I have implemented toaster in my angular 4 project via using this link -> http://www.codershood.info/2017/04/14/showing-notification-using-toaster-angular-2/

It is working absolutely fine when I trigger it via a button click

I added a button e.g

<div class="btn btn-success" (click)="showSuccess()">Success Notification</div>

I added following function

public showSuccess(){    
      this.toastr.success("Success", 'You are on right track.');
  }

It is working absolutely fine but when I try to call it like following ways then it is not working:

EDIT: Added complete component code

import { Component, OnInit,ViewContainerRef } from '@angular/core';
import { FormsModule }   from '@angular/forms';
import {Router} from '@angular/router';
import { AuthService } from '../services/auth.service';
import { Constants } from '../../constants';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import { EmployeeComponent } from '../employee/employee.component';





@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})

export class LoginComponent implements OnInit {

     title = 'GGMD ';
   invalidLogin: boolean;

  constructor(
    private router: Router,
    private authService: AuthService,
    public toastr: ToastsManager, 
    public _vcr: ViewContainerRef) {
    this.toastr.setRootViewContainerRef(_vcr);
  } 

  ngOnInit() {
  }
public showSuccess(){    
      this.toastr.success("Success", 'You are on right track.');
  }

    signIn(credentials){

        let response = this.authService.logIn(credentials);
        if(response.AuthenticationStatus === true){

          switch(response.Role){

               case 'employee':
                this.router.navigate(['/employee']);
                this.toastr.success("Success", 'You are on right track.');
                console.log("Success", 'You are on right track.');
                break;

              case 'manager':
                this.router.navigate(['/manager']);
                console.log('I am manager');
                break;

              default:
                console.log( error);
        }
      }
    }

Log is working and navigating successfully but toaster is not working. I also tried like pass function e.g

 this.router.navigate(['/employee']);
                this.showSuccess()
                console.log("Success", 'You are on right track.');

Solution

  • This will not work since you have changed the root this.router.navigate(['/employee']);

    Try putting toast code before this.router.navigate(['/employee']); something like

          this.toastr.success("Success", 'You are on right track.');
          this.router.navigate(['/employee']);
    

    I am not sure above will work other solution is You can show the toast in employees component constructor