我如何从带有 Angular Material 的服务中显示 MatSnackBar?

Sim*_*ias 4 typescript angular angular-observable angular6 angular-material-6

我正在使用:Angular V6.1.0,Angular Material V6.4.1

我正在尝试捕获 HTTP 错误并使用 MatSnackBar 显示它们。我试图在我的应用程序的每个组件中展示这一点(那里有一个 http 请求)。以免做重复的代码

否则,我应该在每个组件中重复相同的代码,以显示插入错误的 MatSnackBar。

这是我的服务:

import { Injectable } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
// import { HttpClient, HttpErrorResponse, HttpRequest } from '@angular/common/http';
import { Observable, throwError, of, interval, Subject } from 'rxjs';
import { map, catchError, retryWhen, flatMap } from 'rxjs/operators';
import { url, ErrorNotification } from '../globals';
import { MatSnackBar } from '@angular/material';
import { ErrorNotificationComponent } from '../error-notification/error-notification.component';


@Injectable({
  providedIn: 'root'
})
export class XhrErrorHandlerService {
  public subj_notification: Subject<string> = new Subject();

  constructor(
    public snackBar: MatSnackBar
    ) {

  }

  public handleError (error: HttpErrorResponse | any) {
    this.snackBar.open('Error message: '+error.error.error, 'action', {
      duration: 4000,
    });
    return throwError(error);
  }
}
Run Code Online (Sandbox Code Playgroud)

mch*_*l18 5

用这个创建一个服务:

custom-snackbar.service.ts

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

@Injectable()
export class CustomSnackbarService {
    constructor(
      private snackBar: MatSnackBar,
      private zone: NgZone
    ) {
       
    }

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

添加MatSnackBarModuleapp.module.ts

import { MatSnackBarModule } from '@angular/material/snack-bar';

...
imports: [
    BrowserModule,
    AppRoutingModule,
    MatSnackBarModule,
],
...
Run Code Online (Sandbox Code Playgroud)

它还需要在 ngZone 中运行:https : //github.com/angular/material2/issues/9875

然后在error-service.ts

public handleError (error: HttpErrorResponse | any) {
  customSnackbarService.open(error, 'error')
  return throwError(error);
}
   
Run Code Online (Sandbox Code Playgroud)