vinnylinux
vinnylinux

Reputation: 7034

Error handling with Observables in Angular 2

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

Answers (2)

Mardok
Mardok

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

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

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

Related Questions