Heroes教程中的Angular RXJS CatchError

时间:2018-09-24 00:21:18

标签: angular typescript rxjs

我正在运行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传递一个函数,然后catchError返回另一个函数。具体来说,我的问题是关于嵌入式功能return (error: any): Observable<T> => {

为什么handleError返回带有粗箭头符号的函数,而不是仅返回类型T的可观察对象?嵌入式功能的错误参数如何接收数据?

我认为这与调用handleError并返回一个函数有关。因此,本质上catchError接收带有参数error的嵌入式函数,但它在同一范围内还具有变量operationresult?,因此可以与它们一起使用。 catchError然后将数据传递给参数error并返回一个可观察到的T。

RXJS参考将catchError定义为:

catchError<T, R>(selector: (err: any, caught: Observable<T>) =>
ObservableInput<R>): OperatorFunction<T, T | R>

但是我很难解释为什么所有示例都将其传递给函数。

1 个答案:

答案 0 :(得分:3)

您的假设是正确的: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));

catchError需要传递给它的 function ,该函数返回Observable以继续可观察流。返回的可观察对象由of创建。类型T允许错误处理程序根据您传入的后备参数确定Observable发出的值的类型。