问题
I have a method for handle our errors from http requests and it looks like this
public handleError(err: any, caught: Observable<any>): Observable<any> {
//irrelevant code removed
this.logger.debug(err);//example of problem
return caught;
}
It is invoked like this (example method, but shows the error)
public makeHttpCall() {
this.http.get("http://api.exmaple.com/getsomedata")
.map(r=> r.json())
.catch(this.handleError);
}
The problem with the above code is that when calling this.logger.debug(err)
in the handleError
method this
no longer refers to the class the http call was made from but references the CatchSubscriber.
See here:
So i change .catch(this.handleError);
to .catch(this.handlError.bind(this))
;
This works, now when i call this.logger.debug
this
refers to the correct object. The problem is, the http request gets called over and over and over,
see here:
This only happens after applying .bind(this)
I can't figure out why this is happening
*********EDIT*********
Change from .catch(handleError)
to .catch((a,b)=>handleError(a,b))
fixes the reference of this
but the http request just gets spammed over and over, but only when the request fails. If the request succeeds it only happens once.
回答1:
When you pass a function with .catch(this.handleError);
it loses its context this
. See Why do I lose the context of this in Javascript?
Most easily you can fix this by wrapping the function call into a closure.
.catch((err, caught) => this.handleError(err, caught));
来源:https://stackoverflow.com/questions/40149894/angular-2-rxjs-catch-function-callback-binding-to-this-causes-http-request-t