Heroes 教程中的 Angular RXJS CatchError

Die*_*sel 2 rxjs typescript angular

我正在运行 Angular 教程,但我无法理解某一部分实际发生了什么。我从搜索中找到了一些示例,但没有具体回答这个问题。这是代码:

getHeroes (): Observable<Hero[]> {
  return this.http.get<Hero[]>(this.heroesUrl)
    .pipe(
      catchError(this.handleError('getHeroes', []))
    );
} 
Run Code Online (Sandbox Code Playgroud)

接下来是它调用的错误处理程序:

/**
 * 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);
  };
}
Run Code Online (Sandbox Code Playgroud)

我阅读了我可以在 catchError 上找到的文档。我是 Typescript 的新手,但真的很喜欢它。好的,所以问题是为什么我将一个函数传递给 catchError,然后它返回另一个函数。具体来说,我的问题是关于嵌入式功能return (error: any): Observable<T> => {

为什么 handleError 返回一个带有粗箭头符号的函数,而不是一个 T 类型的可观察对象?内嵌函数接收数据的error参数如何?

我认为这与调用 handleError 的事实有关,它返回一个函数。所以本质上 catchError 接收带有参数错误的嵌入函数,但它也有变量operation并且result?在相同的范围内,因此它可以使用这些变量。catchError 然后将数据传递给参数 error 并返回一个可观察的 T。

RXJS 参考将 catchError 定义为:

catchError<T, R>(selector: (err: any, caught: Observable<T>) =>
ObservableInput<R>): OperatorFunction<T, T | R>
Run Code Online (Sandbox Code Playgroud)

但是我很难理解为什么它会像所有示例一样传递一个函数。

Exp*_*lls 5

您的假设是正确的:handleError首先调用该函数,该函数本身会创建一个用于处理错误的函数。有几种其他的方式来写这个可能有助于澄清一点:

// write the function inline:
catchError(error => {
  console.error(error);
  this.log(`getHeroes failed: ${error.message}`);
  return of([]);
});

// call `handleError` first to get the error handler and pass it as a variable.
const errorHandler = this.handleError('getHeroes', []);
return this.http.get<Hero[]>(this.heroesUrl)
  .pipe(catchError(errorHandler));
Run Code Online (Sandbox Code Playgroud)

catchError需要传递给它的函数返回一个 Observable 以继续 observable 流。返回的 observable 是由of. 类型 T 允许错误处理程序根据您传入的回退参数确定 Observable 发出的值的类型。