簡體   English   中英

我可以在服務內使用小吃店嗎?

[英]Can I use a snackbar inside my service?

我想從發生錯誤的api服務調用中獲取錯誤詳細信息。

例如,如果返回的http錯誤是422,我想顯示一條用戶友好的消息。

因此,這是我的服務類別:

@Injectable()
export class TransactionService {

  private baseUrl = 'http://foo.bar/api';
  private body;
  private headers;
  private options;

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

  }

  openSnackBar(message: string) {
    this.snackBar.open(message, null, {duration: 5000});
  }

  errorHandler(error: HttpErrorResponse) {

    console.log(error.status);
    if (error.status === 422) {
      this.openSnackBar('Number already exists');
    } else {
    return Observable.throw(error.message || 'Server Error');
    }
  }

  SubmitTransaction(transactionRequest: ITransactionRequestObj): Observable<TransactionResponse> {
    this.body =  JSON.stringify(transactionRequest);
    this.headers = new HttpHeaders().set('Content-Type', 'application/json');
    this.headers.append('Accept', 'application/json');
    this.options = new RequestOptions({headers: this.headers});
    console.log(JSON.stringify(transactionRequest));
    return this.http.post<TransactionResponse>(this.baseUrl + '/transactions/new',  this.body, this.options)
                .catch(this.errorHandler);
  }

}

我做了一個console.log,當發生422錯誤時,我確實獲得了正確的錯誤狀態編號。 但是,小吃欄不會彈出,因為我收到此錯誤:

core.js:1448 ERROR TypeError: this.openSnackBar is not a function
    at CatchSubscriber.TransactionService.errorHandler [as selector] (transaction.service.ts:49)
    at CatchSubscriber.error (catchError.js:105)
    at MapSubscriber.Subscriber._error (Subscriber.js:131)
    at MapSubscriber.Subscriber.error (Subscriber.js:105)
    at FilterSubscriber.Subscriber._error (Subscriber.js:131)
    at FilterSubscriber.Subscriber.error (Subscriber.js:105)
    at MergeMapSubscriber.OuterSubscriber.notifyError (OuterSubscriber.js:24)
    at InnerSubscriber._error (InnerSubscriber.js:28)
    at InnerSubscriber.Subscriber.error (Subscriber.js:105)
    at XMLHttpRequest.onLoad (http.js:2283)

是因為我不應該/不能在服務內部使用小吃店(僅組件)?

相同的小吃店代碼在我的組件內可以正常工作,但是我無法在組件內獲取錯誤狀態。

這也是我的組件類中的服務調用:

this._transactionService.SubmitTransaction(this.transactionObj).subscribe(data => {
        if (data._errorDetails._status === '201') {
          //do some action 
        }
      }, (err) => {
        console.log(err);
        if (err.status === 422) { //also tried this inside my component err.status is undefined. However err is the server error message.
        //do some action 
        }
      });

我假設您需要綁定this上下文才能使其正常工作:

.catch(this.errorHandler.bind(this));

或者,您也可以使用以下選項:

.catch((e) => this.errorHandler(e));

或本地胖箭頭功能:

errorHandler = (error: HttpErrorResponse) => {
  ...
}

有關更多詳細信息,請參見:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM