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); } ... }
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.
MatSnackBar is a service for displaying snack-bar notifications. Basic snack-bar.
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');
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With