如何在服务中使用SnackBar以在Angular 2中的每个组件中使用 [英] How to use SnackBar on service to use in every component in Angular 2
本文介绍了如何在服务中使用SnackBar以在Angular 2中的每个组件中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个工作的快餐栏,但是它仅在每个组件上,我想将其添加到我的服务中,所以我将其称为.这是我的component.ts
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);
}
...
}
推荐答案
如果您希望SnackBar在整个应用程序中正常工作,则应将其放入app.component并与服务进行通信.
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:
notification.service.ts:
public notification$: Subject<string> = new Subject();
app.component.ts:
app.component.ts:
constructor(
private notificationService: NotificationService, private snackBar: MatSnackBar
) {
this.notificationService.notification$.subscribe(message => {
this.snackBar.open(message);
});
}
any.component.ts:
any.component.ts:
this.notificationService.notification$.next('this is a notification');
这篇关于如何在服务中使用SnackBar以在Angular 2中的每个组件中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文