我正在阅读本教程:
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函数逻辑的详细信息,越好。我想深入研究这件事。
发布于 2018-06-23 02:56:54
当只有一个参数名时,括号是可选的,您可以从函数中看到更多细节
(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 }属
这允许我们捕获用户提供的类型,这是一种类型检查方式,您可以称它为多种方式之一。
参考文献
在本例中,我们再次使用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);
};
}
https://stackoverflow.com/questions/50997081
复制相似问题