How to use SnackBar on service to use in every component in Angular 2

Storm Spirit picture Storm Spirit · Mar 13, 2017 · Viewed 16.7k times · Source

I have a working snackbar, but it is only on each component, I want to add it on my service so I will just call it. This is my sample on my component.ts

import { MdSnackBar, MdSnackBarRef } from '@angular/material';
...
export class EmployeeListComponent implements OnInit {
  public toastRef: MdSnackBarRef<any>;
  constructor(private _activatedRoute:ActivatedRoute,private router: Router, private http:PMISHttpService, private toast: MdSnackBar) {

  ngOnInit() {
    this.notify('test');
  }
  ...
  notify (text: string) {
    this.toastRef = this.toast.open(text, null);
    setTimeout(() => {
      this.toastRef.dismiss();
    }, 5000);
  }
  ...
}

Answer

Ploppy picture Ploppy · Mar 13, 2017

If you want a SnackBar to work across your entire app, you should put it into your app.component and communicate with it with a service.

notification.service.ts:

public notification$: Subject<string> = new Subject();

app.component.ts:

constructor(
  private notificationService: NotificationService, private snackBar: MatSnackBar
) {
  this.notificationService.notification$.subscribe(message => {
    this.snackBar.open(message);
  });
}

any.component.ts:

this.notificationService.notification$.next('this is a notification');