Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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);   }   ... } 
like image 826
Storm Spirit Avatar asked Mar 13 '17 10:03

Storm Spirit


People also ask

How do I use snackbar in service?

Import the snackBarService and inject it inside the constructor of the component, in which you want to use the Snackbar. This will create an instance of the service say snackBService. Now call the openSnackBar function wherever it is required, with the help of snackBService.

What is MatSnackBar?

MatSnackBar is a service for displaying snack-bar notifications. Basic snack-bar.


Video Answer


2 Answers

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'); 
like image 104
Ploppy Avatar answered Oct 02 '22 16:10

Ploppy


To have it everywhere, create a service for it. Also you should use the snackbar config for setting duration and make snackbar public:

import {Injectable, NgZone} from '@angular/core'; import {MatSnackBar} from '@angular/material';  @Injectable() export class CustomSnackbarService {      constructor(       public snackBar: MatSnackBar,       private zone: NgZone     ) {}      public open(message, action = 'success', duration = 50000) {         this.zone.run(() => {             this.snackBar.open(message, action, { duration });         });     } } 

Also it needs to be run in ngZone: https://github.com/angular/material2/issues/9875

Then in the component:

customSnackbarService.open('hello')

like image 38
mchl18 Avatar answered Oct 02 '22 16:10

mchl18