Angular tutorial中有一个建议的错误处理程序,如果发生错误,该错误处理程序可以将默认值返回给调用方。
/**
* 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);
};
}
现在我使用async / await进行了网络服务调用:
public async getItemsAsync() {
try {
return await this.http.get<string[]>("/some/url").toPromise();
}
catch (error) {
this.handleError<string[]>('getItemsAsync',[]);
}
}
为了能够从我的错误处理程序中返回默认值,我必须更改什么?
private handleError<T>(operation = 'operation',result?: T) {
console.log(`${operation} failed: ${error.message}`);
// let the app keep running by returning an empty result.
return result as T;
}
我应该返回Observable
还是Promise
?我都尝试过,但是没有编译。当前,string[]
未返回。我只会得到undefined
。