如何在服务上使用 SnackBar 以在 Angular 2 中的每个组件中使用 [英] How to use SnackBar on service to use in every component in Angular 2

查看:38
本文介绍了如何在服务上使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆