A service in angular has special duties such as fetching and pushing data from the server and to the server. The service can be used by any components.
Handle exception
To hand service exceptions we need the following two libraraies
import {catchError} from 'rxjs/operators'; import { throwError } from 'rxjs';
In the service.ts file we need to handle the error using pipe function as follows
.... Post(model : Model){ return this._http.post ('http:\apiurl',model).pipe(catchError(this.ErrorHandler)); } ErrorHandler(error: HttpErrorResponse): any { return throwError(error); }
Catching the error in component
For the receiving the error in a component , we need to create property then assign the error object to the property. So that we can bind it to the template.
... this._service.Post(this.data).subscribe((data: any) => console.log('Success', data), (error: any) => this.errorMsg = error.statusText); }
Don’t forget to visit the source code page