2017-03-13 10 views
1

私は働くスナックバーを持っていますが、それは各コンポーネントにしかありません。これは、スナックバーがあなたの全体のアプリ間で動作する場合、あなたはapp.componentにそれを入れて、サービスでそれと通信する必要があり、私のcomponent.tsSnackBar on Serviceを使用して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); 
    } 
    ... 
} 

答えて

5

の私のサンプルです。

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

機能を通知入れるには?申し訳ありません –

+0

グローバルサービスを作成します。グローバルサービスは、 'subj_notification' rxjs件名を持ち、app.componentはsnackBarを持ち、 'subj_notification'に登録されています。この時点で、アプリ内の任意のコンポーネントがサービスのsubj_notification.next()を呼び出すことができ、アプリコンポーネントにはサブジェクトの変更が通知されます。 – Ploppy

関連する問題