2017-03-13 2 views
1

J'ai un snack-bar de travail, mais c'est seulement sur chaque composant, je veux l'ajouter sur mon service, donc je vais l'appeler. Ceci est mon exemple sur mon component.tsComment utiliser SnackBar sur le service à utiliser dans chaque composant dans Angular 2

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); 
    } 
    ... 
} 

Répondre

5

Si vous voulez un SnackBar à travailler sur votre application entière, vous devez mettre dans votre app.component et de communiquer avec lui avec un service.

notification.service.ts:

public subj_notification: Subject<string> = new Subject(); 

app.component.ts:

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

any.component.ts:

this.notificationService.subj_notification.next('this is a notification'); 
+0

où mettre la fonction Notify? désolé d'être débutant –

+0

Vous créez un service global, qui a un objet rxjs 'subj_notification', votre composant application a le snackBar et est abonné à 'subj_notification'. À ce stade, tout composant de votre application peut appeler subj_notification.next() du service et votre composant d'application sera informé du changement d'objet. – Ploppy