Angular - 理解英雄之旅的handleError函数

dav*_*esp 5 rxjs typescript angular

我正在阅读本教程:https :
//angular.io/tutorial/toh-pt6#error-handling

我无法完全理解error-handling函数:handleError.

该函数用于此代码片段:

/** GET heroes from the server */
getHeroes (): Observable<Hero[]> {
  return this.http.get<Hero[]>(this.heroesUrl)
    .pipe(
      tap(heroes => this.log(`fetched heroes`)),
      catchError(this.handleError('getHeroes', []))
    );
}
Run Code Online (Sandbox Code Playgroud)

这是handleError功能:

/**
 * 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)

我不明白什么意思:

return (error: any): Observable<T> => { ... }?

是不是类似于:

return ((error: any): Observable<T>) => { ... }?

我只想知道函数的来源和命运是什么。

你能提供的关于handleError函数逻辑的细节越多越好。我想深入探讨这一点。

Chu*_* Li 3

当只有一个参数名称时,括号是可选的,您可以从arrow_functions查看更多详细信息

\n\n
(param1, param2, \xe2\x80\xa6, paramN) => { statements } \n(param1, param2, \xe2\x80\xa6, paramN) => expression\n// equivalent to: => { return expression; } \n\n// Parentheses are optional when there\'s only one parameter name:\n(singleParam) => { statements }\nsingleParam => { statements }\n\n// The parameter list for a function with no parameters should be written with a pair of parentheses.\n() => { statements }\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n\n

通用的

\n\n

这允许我们捕获用户提供的类型,这是 Typescript 的一种类型检查方式,您可以将其称为多种方式之一。

\n\n

参考

\n\n\n\n
\n\n

在此示例中,我们再次使用 T 作为返回类型。通过检查,我们现在可以看到该类型用于返回类型

\n\n
private handleError<T> (operation = \'operation\', result?: T) {\n  return (error: any): Observable<T> => {\n\n    ...\n\n    return of(result as T);\n  };\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n\n

在下面的例子中,我将解释通用如何使用stringnumber输入

\n\n

\r\n
\r\n
(param1, param2, \xe2\x80\xa6, paramN) => { statements } \n(param1, param2, \xe2\x80\xa6, paramN) => expression\n// equivalent to: => { return expression; } \n\n// Parentheses are optional when there\'s only one parameter name:\n(singleParam) => { statements }\nsingleParam => { statements }\n\n// The parameter list for a function with no parameters should be written with a pair of parentheses.\n() => { statements }\n
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n