我试图将HTTP请求中可能发生的任何错误传递给我所有服务的公共日志记录服务:
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);
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,在notifyErrors方法内部,this丢失了.我已经尝试将其定义为胖箭头,但我从TS编译器中获取了类型错误.我已经使用了Observable文档中的确切语法.
如果传递函数引用,则需要修复 this
.catch(this.notifyErrors.bind(this));
Run Code Online (Sandbox Code Playgroud)
或者
.catch(() => this.notifyErrors());
Run Code Online (Sandbox Code Playgroud)
另请参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions