I have developed a method to handle errors resulting from http requests. Here is an example of how it functions:
public handleError(err: any, caught: Observable<any>): Observable<any> {
//irrelevant code omitted
this.logger.debug(err);//example of problem
return caught;
}
This method is called in the following manner (a sample method illustrating the error):
public makeHttpCall() {
this.http.get("http://api.exmaple.com/getsomedata")
.map(r=> r.json())
.catch(this.handleError);
}
The issue with the above code arises when this.logger.debug(err)
is executed within the handleError
method. At this point, instead of referring to the class where the http call originated from, this
now refers to the CatchSubscriber.
View the reference change: https://i.stack.imgur.com/9yCzI.png
To resolve this, I modified .catch(this.handleError);
to
.catch(this.handlError.bind(this))
;
After making this adjustment, this.logger.debug
properly references the correct object. However, there is a new issue - the http request is being repeatedly triggered,
as shown here:
https://i.stack.imgur.com/3pxPj.png
This repetitive calling only occurs after using .bind(this)
I am struggling to understand why this behavior is occurring
*********EDIT*********
Switching from .catch(handleError)
to
.catch((a,b)=>handleError(a,b))
resolves the this
reference problem but results in continuous spamming of the http request whenever it fails. If the request succeeds, it only triggers once.