在使用中打开角材小吃店

时间:2019-02-02 15:07:52

标签: angular typescript angular-material

我想通过Snackbar向用户显示错误。通过组件打开小吃店时,这完全没问题:

export class AppComponent implements OnInit {

    constructor(private snackBar: MatSnackBar) {
    }

    ngOnInit() {
        this.snackBar.open('message');
    }
}

但是当我想在DataService中打开Snackbar时,会引发此错误:

ERROR TypeError: Cannot read property 'open' of undefined

我的DataService看起来像这样:

export class DataService {

  private api = 'https://localhost:5001/api/';

  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  };

  constructor(private http: HttpClient,
              private snackBar: MatSnackBar) {
  }

  getData() {
    return this.http.get(this.api, this.httpOptions)
      .pipe(
        retry(3), // retry a failed request up to 3 times
        catchError(this.handleError) // then handle the error
      );
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred.
      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,
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }

    this.snackBar.open('Something bad happened, please try again later.');

    // return an observable with a user-facing error message
    return throwError(
      'Something bad happened; please try again later.');
  }
}

因此,在第三次尝试获取数据后,它进入handleError()并应打开“ SnackBar”,提示“发生了某些不良情况,请稍后再试。”

1 个答案:

答案 0 :(得分:0)

之所以会发生这种情况,是因为catchError中的当前作用域不是该类本身,因此不是

this.snackbar

未定义。要解决此问题,有2种方法

方法1:

您可以从另一个函数内部返回回调函数,以将范围保留为

private handleError() {
    return (error: HttpErrorResponse) => {
        //your logic
    }
}

并将您的catchError方法更改为

catchError(this.handleError())  //note the parenthesis on handleError

方法2:

只需将catchError中的回调方法绑定到this即可

this.ErrorHandler.bind(this)
相关问题