angular - 我可以在我的服务中使用小吃店吗?
问题描述
如果发生错误,我想从调用 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(只有组件?)?
相同的小吃店代码在我的组件中运行良好,但我无法在组件中获取错误状态。
这也是我的组件类中的服务调用:
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) => {
...
}
有关更多详细信息,请参阅:
推荐阅读
- intellij-idea - 将 IntelliJ 的控制台输出通过管道传输到脚本
- docker - 运行没有入口点的命令
- python - 创建一个列,它是熊猫中两个字符串列的差异
- python - 如果输入不足,如何遍历文件并引发自定义异常?
- python - 如何对字符串列表中的元素进行编号并返回一个新列表?
- google-app-engine - App Engine 如何防止实例内存不足?
- javascript - 使用 Heroku Redis 的 BullMQ 不会触发 QueueEvents
- django - 在 nginx 中设置“X-Forwarded-For”标头的目的是什么
- c# - C# 流控制 devCodeCamp 任务
- asp.net - FindControl 在 Listview Null 异常中不起作用