Reputation: 7034
I'm trying to pass any errors that might occur in an HTTP request to a common logging service from all my services:
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
constructor(logger: LoggerService) { }
doSomething(): Observable<any> {
return this.http
.post('/foo/bar', {})
.catch(this.notifyErrors);
}
protected notifyErrors(error: any): Observable<any> {
this.logger.log(error);
return Observable.throw(error);
}
Unfortunately, inside the notifyErrors
method, this
is lost. I've tried defining this as a fat arrow, but i get type errors from the TS compiler. I've used the exact syntax in the Observable documentation.
Upvotes: 5
Views: 1975
Reputation: 1460
I have not run your code, but if you want to access this, you may have to pass it in.
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
constructor(logger: LoggerService) { }
doSomething(): Observable<any> {
return this.http
.post('/foo/bar', {})
.catch(err => {
this.notifyErrors(err, this);
});
}
protected notifyErrors(error, that): Observable<any> {
that.logger.log(error);
return Observable.throw(error);
}
Upvotes: -1
Reputation: 658017
If you pass function references, you need to fix this
.catch(this.notifyErrors.bind(this));
or alternatively
.catch(() => this.notifyErrors());
See also https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Upvotes: 8