我正在运行 Angular 教程,但我无法理解某一部分中实际发生的情况。我通过搜索找到了一些例子,但没有具体回答这个问题。这是代码:
getHeroes (): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
catchError(this.handleError('getHeroes', []))
);
}
接下来是它调用的错误处理程序:
/**
* Handle Http operation that failed.
* Let the app continue.
* @param operation - name of the operation that failed
* @param result - optional value to return as the observable result
*/
private handleError<T> (operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// TODO: better job of transforming error for user consumption
this.log(`${operation} failed: ${error.message}`);
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
我阅读了在 catchError 上可以找到的文档。我是 Typescript 的新手,但我真的很喜欢它。好的,问题是为什么我将一个函数传递给 catchError,然后它返回另一个函数。具体来说,我的问题是关于嵌入式功能return (error: any): Observable<T> => {
为什么handleError返回一个带有粗箭头表示法的函数而不是仅仅一个T类型的可观察值?嵌入函数接收数据的error参数如何?
我认为这与调用handleError有关,它返回一个函数。所以本质上 catchError 接收带有参数 error 的嵌入函数,但它也有变量operation
and result?
在相同的范围内,因此它可以与这些一起工作。 catchError 然后将数据传递给参数 error 并返回一个可观察的 T。
RXJS 参考将 catchError 定义为:
catchError<T, R>(selector: (err: any, caught: Observable<T>) =>
ObservableInput<R>): OperatorFunction<T, T | R>
但我很难解释为什么它会像所有示例一样被传递给一个函数。