Error handling with Observables in Angular 2

I am trying to pass on any errors that may occur in the HTTP request to the general 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, notifyErrors is lost. I tried to define this as a bold arrow, but I get type errors from the TS compiler. I used the exact syntax in the Observable documentation.

+5
source share
2 answers

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

+8
source

I do not run your code, but if you want to access it, you may need to pass it.

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

Source: https://habr.com/ru/post/1266083/


All Articles