如何在服务上使用SnackBar在Angular 2中的每个组件中使用

Sto*_*rit 12 snackbar angular-material2 angular

我有一个工作的零食吧,但它只在每个组件上,我想在我的服务上添加它,所以我会打电话给它.这是我的样本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);
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)

Plo*_*ppy 15

如果您希望SnackBar在整个应用程序中运行,您应该将其放入app.component并与服务进行通信.

notification.service.ts:

public notification$: Subject<string> = new Subject();
Run Code Online (Sandbox Code Playgroud)

app.component.ts:

constructor(
  private notificationService: NotificationService, private snackBar: MatSnackBar
) {
  this.notificationService.notification$.subscribe(message => {
    this.snackBar.open(message);
  });
}
Run Code Online (Sandbox Code Playgroud)

any.component.ts:

this.notificationService.notification$.next('this is a notification');
Run Code Online (Sandbox Code Playgroud)


Har*_*lsi 7

您可以轻松地做到这一点。请在下面找到我在我的一个项目中使用的示例的示例,它运行良好

import { Injectable } from '@angular/core';
import {
  MatSnackBar,
  MatSnackBarConfig,
  MatSnackBarHorizontalPosition,
  MatSnackBarVerticalPosition,
  MatSnackBarRef
} from '@angular/material';

@Injectable()
export class SnackBarService {

  snackBarConfig: MatSnackBarConfig;
  snackBarRef: MatSnackBarRef<any>;
  horizontalPosition: MatSnackBarHorizontalPosition = 'center';
  verticalPosition: MatSnackBarVerticalPosition = 'top';
  snackBarAutoHide = '1500';

  constructor(private snackBar: MatSnackBar) { }

  openSnackBar(message) {
    this.snackBarConfig = new MatSnackBarConfig();
    this.snackBarConfig.horizontalPosition = this.horizontalPosition;
    this.snackBarConfig.verticalPosition = this.verticalPosition;
    this.snackBarConfig.duration = parseInt(this.snackBarAutoHide, 0);
    this.snackBarConfig.panelClass = 'custom-snackbar';
    this.snackBarRef = this.snackBar.open(message, '', this.snackBarConfig);
}

}
Run Code Online (Sandbox Code Playgroud)

现在,您只需将该服务注入您的组件或您想使用它的任何地方,并使用您想显示的消息调用 openSnackBar() 方法。

希望这可以帮助!!


mch*_*l18 5

要无处不在,为其创建服务。另外,您还应该使用Snackbar配置来设置持续时间并公开Snakebar:

import {Injectable, NgZone} from '@angular/core';
import {MatSnackBar} from '@angular/material';

@Injectable()
export class CustomSnackbarService {

    constructor(
      public snackBar: MatSnackBar,
      private zone: NgZone
    ) {}

    public open(message, action = 'success', duration = 50000) {
        this.zone.run(() => {
            this.snackBar.open(message, action, { duration });
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

它还需要在以下位置运行ngZonehttps : //github.com/angular/material2/issues/9875

然后在组件中:

customSnackbarService.open('hello')


Tom*_*káč 5

这是我的工作示例(Angular 11,Angular Material 11.0.1)。

最重要的部分是在app.module.ts中包含 MatSnackBarModule。另外,不要忘记导入BrowserAnimationsModule

import { MatSnackBarModule } from '@angular/material/snack-bar';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
  imports: [
    MatSnackBarModule,
    BrowserAnimationsModule
    ...
  ],
Run Code Online (Sandbox Code Playgroud)

然后,我的服务看起来像这样

import { Injectable } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';

@Injectable({
  providedIn: 'root'
})
export class SnackbarService {

  constructor(
    private _snackBar: MatSnackBar) {
  }

  error(message: string) {
    return this._snackBar.open(message, undefined, {panelClass: ['snackbar-error']});
  }

  success(message: string) {
    return this._snackBar.open(message, undefined, {panelClass: ['snackbar-success']});
  }

  info(message: string) {
    return this._snackBar.open(message, undefined, {panelClass: ['snackbar-info']});
  }
}

Run Code Online (Sandbox Code Playgroud)

为了定义样式,我将这些添加到了 style.scss

.mat-simple-snackbar {
  font-size: 1.2em;
  color: white;
}

.snackbar-error {
  background-color: red;
}

.snackbar-success {
  background-color: green;
}

.snackbar-info {
  background-color: blue;
}

Run Code Online (Sandbox Code Playgroud)

这样,我现在可以从代码中的任何位置(包括来自其他模块的组件)调用 SnackBar。用法示例:

import { Component } from '@angular/core';
import { AuthService } from 'src/app/services/auth/auth.service';
import { SnackbarService } from 'src/app/services/snackbar.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent {

  loginForm: any;

  constructor(private authService: AuthService, private snackbar: SnackbarService) { }

  onSubmit() {
      this.authService.login(this.loginForm).subscribe(res => {
        this.snackbar.success('Logged in');
      }, e => {
        this.snackbar.error('Login failed');
      });
  }

}

Run Code Online (Sandbox Code Playgroud)