我在我的服务中使用 angular6 HTTPClient,并希望将 Observable 的 next 和 err 路径维护给订阅者。
例如,我的组件看起来像这样:
private myFun(query: string) {
this.myService.login(data).subscribe(next => {
// Do successful stuff
console.log('Got the data: ' + next);
},
err => {
// Handle all errors here
console.error('good luck next time')
});
}
我的服务正在使用管道以及地图和 catchError。
private findData(in: string): Observable<string> {
return this.http.post<string>(self.url, '')
.pipe(
map( response => {
//Check the data is valid
if (this.dataValid(response)){
return this.convertedData(response);
} else {
throw new Error('failed parsing data');
}
}),
catchError(this.handleError)
);
}
我可以检测到解析问题并通过 catchError 引发错误,但我很难理解的是如何处理 catchError。
错误处理程序如下所示:
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// Client Side Error
console.error('Client side error:', error.error.message);
} else if (error.message === 'failed parsing data') {
// Client Side Processing Error
console.error(error.message);
return throwError(error.message);
} else {
// Service Side Error
console.error(`Server returned code ${error.status}, ` + `body was: ${error.error}`);
}
// return an observable error message
return throwError('failed to contact server');
}
它完成了这项工作,但我不禁想到必须有更好、更 Angular/RxJS 的方式来做到这一点。
我所期望的是命中错误处理程序的“error.error instanceof ErrorEvent”路径。我不明白“错误:HttpErrorResponse”参数是如何更新的 - 我只是抛出一个“新错误('解析数据失败');”。
有什么建议/建议吗?