Going through the Angular docs for handling HTTP error responses in a service I came across something like this:
getContext(){
return this.http.post(this.testUrl, {})
.pipe(
catchError(this.handleError)
)
}
handleError(error: HttpErrorResponse){
if(error.error instanceof ErrorEvent){
console.log('An error occurred:', error.error.message);
} else {
console.log(
`Backend returned code ${error.status}` +
`body was ${error.error}`
)
}
return throwError('Need to fix!');
}
I was wondering why this.handleError
is not passed an argument (an HTTPErrorResponse
) and how it works without receiving one?
The handleError
method is passed as a callback to catchError
.
doSomething(callback) {
// Call the callback with arguments
callback('Hello world');
}
saySomething(param) {
console.log(param);
}
doSomething(saySomething);
Try to imagine catchError
is doing the same for your handleError
function. Will call it with arguments, you just specify what function to be called when an error occurs.
Good luck!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.