【发布时间】:2019-04-17 22:56:35
【问题描述】:
通过 Angular 文档处理服务中的 HTTP 错误响应,我遇到了这样的事情:
getContext(){
return this.http.post(this.testUrl, {})
.pipe(
catchError(this.handleError)
)
}
handleError(error: HttpErrorResponse){
if(error.error instanceof ErrorEvent){
console.log('An error occurred:', error.error.message);
} else {
console.log(
`Backend returned code ${error.status}` +
`body was ${error.error}`
)
}
return throwError('Need to fix!');
}
我想知道为什么 this.handleError 没有传递参数(HTTPErrorResponse)以及它如何在不接收参数的情况下工作?
【问题讨论】:
-
catchError(this.handleError)等于 here 到catchError(error => this.handleError(error)) -
@Kos 啊,我明白了。当只有一个参数传递给只接收一个参数的函数时,是否使用此语法? IE。 catchError(function(error){ this.handleError(error) })
-
是的!但是有一个重要的区别:当像
catchError(this.handleError)这样调用时,调用上下文将是未定义的。将其阅读为catchError(err => { const fn = this.handleError; return fn(err); })。这里 this 将不再是调用的上下文,上下文将为空。所以你将无法在handleError方法中引用this。 -
@Kos 明白了!谢谢。
-
关于如何在rxjs中正确抛出我可以推荐两篇文章:medium.com/@alexanderposhtaruk/…和blog.angularindepth.com/…