I am trying to retrieve error details from a service call that communicates with an API in case of an error occurrence.
For example, if the HTTP error returned is 422, I want to display a user-friendly message.
Below is my service class:
@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);
}
}
While I can see the correct error status number when a 422 error occurs, I encounter an issue where the snackbar doesn't pop up. The following error is displayed instead:
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 makes me wonder if using a snackbar inside a service is not recommended or even possible, and only components are suitable for it?
The same snackbar code works without issues within my component, although I face difficulty accessing the error status within the component. Here's the service call snippet from my component class as well:
this._transactionService.SubmitTransaction(this.transactionObj).subscribe(data => {
if (data._errorDetails._status === '201') {
// perform specific action
}
}, (err) => {
console.log(err);
if (err.status === 422) { //attempted this within my component but err.status turns out to be undefined. However, the error message from the server is present in err.
//perform another action
}
});