我可以在服务中使用小吃吧吗?

我希望从我的服务调用中获取错误详细信息,如果发生错误则调用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)

是因为我不应该/不能在我的服务中使用snackbar(只有组件?)?

相同的snackbar代码在我的组件内工作正常,但我无法在组件中获取错误状态 .

这是我的组件类中的服务调用:

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 
        }
      });

回答(1)

2 years ago

我假设您需要绑定正确的 this 上下文才能正常工作:

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

或者您也可以使用以下选项:

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

或局部脂肪箭头功能:

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

有关更多详情,请参阅