Angular show snackbar after navigation

Viewed 3031

I have two components. In the first one on successful server response I want to do the following:

this.router.navigate(['']);
this.snackBarMessage = 'Successfully submitted';

Then the page is being redirected to another component and I would like to show the snackBarMessage message just there e.g (ngOnInit())

Something like that:

this.snackBarService.openSnackBar(snackBarMessage, 'Close', 9999999);

My snackBarService:

import { Injectable } from '@angular/core';
import { MatSnackBar } from '@angular/material';

@Injectable({
  providedIn: 'root'
})
export class SnackBarService {

  constructor(private matSnackBar: MatSnackBar) { }

  openSnackBar(message: string, action: string, duration?: number) {
    this.matSnackBar.open(message, action, { duration });
  }
}

How can I achieve that? How can I pass snackBarMessage to another component after navigation?

2 Answers

this.router.navigate([``]) returns a promise to which you can subscribe to. This promise will be executed after the navigation was successful. Please see this Documentation for further information.

this.router.navigate(['']).then((navigated: boolean) => {
    if(navigated) {
      this.snackBarService.openSnackBar(snackBarMessage, 'Close', 9999999);
    }
});

You may show the message and then navigate:

Using the afterDismissed() method:

this.snackBar.open('msg', 'close', {
                  duration: 2000
                }).afterDismissed().subscribe(()=>{
                  this.router.navigate(['']);
                });
Related