我正在阅读本教程:
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', []))
);
}
这是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);
};
}
我不明白这是什么意思
return (error: any): Observable<T> => { ... }
?
类似于以下内容:
return ((error: any): Observable<T>) => { ... }
?
我只想知道功能的来源和目的。
您可以提供有关handleError
函数的逻辑的详细信息越多越好。我想深入探讨这个问题。
答案 0 :(得分:1)
只有一个参数名称时,括号是可选的,您可以从arrow_functions中看到更多详细信息
(param1, param2, …, paramN) => { statements }
(param1, param2, …, paramN) => expression
// equivalent to: => { return expression; }
// Parentheses are optional when there's only one parameter name:
(singleParam) => { statements }
singleParam => { statements }
// The parameter list for a function with no parameters should be written with a pair of parentheses.
() => { statements }
通用
这使我们能够捕获用户提供的类型,这是Typescript的类型检查方式,您可以将其称为多种方式之一。
参考
在此示例中,我们再次使用T作为返回类型。通过检查,我们现在可以看到该类型用于返回类型
private handleError<T> (operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
...
return of(result as T);
};
}
在下面的示例中,我将解释泛型如何使用string
和number
类型的
// string type (maybe you want to return some mesage when error)
getHeroes (): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
...
catchError(this.handleError<string>('getHeroes', 'my result....'))
);
}
// similar to : private handleError<number>(operation = 'operation', result ? : number)
// return (error: any): Observable <number> => { ...
private handleError<T>(operation = 'operation', result? : T) {
return (error: any): Observable<T> => {
...
// result: my result....
return of(result);
};
}
----
// number type (maybe you want to return ID:1234) when error
getHeroes (): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
...
catchError(this.handleError<string>('getHeroes', '1234'))
);
}
// similar to : private handleError<string>(operation = 'operation', result ? : string)
// return (error: any): Observable <string> => { ...
private handleError<T>(operation = 'operation', result? : T) {
return (error: any): Observable<T> => {
...
// reuslt: 1234
return of(result);
};
}