5

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.

1
  • 1
    Gunter, has a more elegant solution. I like his better than mine. Commented Mar 29, 2017 at 16:42

2 Answers 2

8

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

Sign up to request clarification or add additional context in comments.

Comments

-1

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);
}

2 Comments

err => { this.notifyErrors(err, this); } does not work. The compiler gives me: Argument of type '(err: any) => void' is not assignable to parameter of type '(err: any, caught: Observable<Response>) => ObservableInput<{}>'.
Or Use Gunters answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.