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

前端 未结 4 2131
情深已故
情深已故 2020-12-15 06:19

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

4条回答
  •  北海茫月
    2020-12-15 06:41

    I am using version version": "2.0.0-beta.10", This is what I did to get it working

    In ApModule

    import { NotificationService } from "./notification/notification.service";
    import { MdSnackBarModule } from "@angular/material";
    
    @NgModule({
      imports: [
        MdSnackBarModule,
        FormsModule
      ],
      providers: [WebService, NotificationService]
    

    Create a notification service as suggested in previous post

    import { Injectable } from "@angular/core";
    import {
      MdSnackBar,
      MdSnackBarConfig,
      // MdSnackBarHorizontalPosition,
      // MdSnackBarVerticalPosition,
      MdSnackBarRef
    } from "@angular/material";
    
    @Injectable()
    export class NotificationService {
      private snackBarConfig: MdSnackBarConfig;
      private snackBarRef: MdSnackBarRef;
        private snackBarAutoHide = "5000"; //milliseconds for notification , 5 secs
    
      constructor(private sb: MdSnackBar) {}
    
      openSnackBar(message) {
        this.snackBarConfig = new MdSnackBarConfig();
        //this.snackBarConfig.horizontalPosition = this.horizontalPosition; only in current version Demo uses very old version . need to upgrade later
        //this.snackBarConfig.verticalPosition = this.verticalPosition; only in current version Demo uses very old version . need to upgrade later
        this.snackBarConfig.duration = parseInt(this.snackBarAutoHide, 0);
          this.sb.open(message, "", this.snackBarConfig);
      }
    }
    

    Consume service as shown below

       this.notify.openSnackBar(message);
    

提交回复
热议问题