![](/img/trans.png)
[英]How can I use an AlertService (mat snackbar for error messages) inside another service?
[英]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.