繁体   English   中英

角形材料小吃店正在使用中?

[英]Angular material snackbar in service?

我想处理 http 错误消息并在服务中使用 Angular 材料小吃店模块显示它们。 我不想在组件中做所有这些重复的工作。 我该怎么做? 我收到以下错误: ERROR TypeError: this.openSnackBar is not a function 请注意,它在组件中工作正常。

private handleError(error: HttpErrorResponse) {
    let message:string = "Something bad happened; please try again later."
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong.
     if(error.status == 404){

        this.openSnackBar('No data found!','Dismiss')
     }

    }
    console.log(error)
    // Return an observable with a user-facing error message.
    return throwError(message);
  }

openSnackBar(message: string, action: string) {
    this._snackBar.open(message, action, {
      duration: 2000,
    });
  }

MatSnackBar 只是一项服务,因此您需要确保几件事

  1. 导入 MatSnackBarModule

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

  2. 注入 MatSnackBar 服务。

  3. 如果您在服务中使用它,请确保使用可注入装饰器标记该服务。

例子

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

  constructor(private _snackBar: MatSnackBar){ }
   logError(message:string){
      this._snackBar.open(message,'Dismiss')
   }
} 

stackblitz 演示 🚀

更新了🌟

看起来您将 handleError 作为函数引用传递,在这种情况下 this 将引用其他对象,并且您会收到类似您所拥有的错误

一个快速的解决方法是使用这样的箭头函数

private handleError = (error: HttpErrorResponse) => {
   ....
}

openSnackBar(message: string, action: string) {
...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM