【发布时间】:2019-01-24 09:29:19
【问题描述】:
在 Angular 文档中,他们声明您必须在提供的选项上指定 observe: "response" 才能获得完整的 http 响应,我在这里做了:
constructor(private service: new () => T,
private http: HttpClient,
private httpErrorHandler: HttpErrorHandlerService,
){
this._handleError = this.httpErrorHandler.createHandleError(this.service.name);
}
private _handleError: HandleError;
//...other code
delete(resourceNameOrId: number | string): Observable<HttpErrorResponse>{
return this.http.delete<T>(this._url + resourceNameOrId, {
observe: "response"
}).pipe(
catchError(this._handleError(`delete`, null))
);
}
handleError 函数是在这个服务中定义的:
export type HandleError = <T> (operation?: string, result?: T) => (error: HttpErrorResponse) => Observable<T>;
@Injectable({
providedIn: 'root'
})
export class HttpErrorHandlerService {
constructor(private errorService: ErrorService, private modalService: NzModalService) { }
createHandleError = (serviceName = '') => <T> (operation = 'operation', result = {} as T) => this.handleError(serviceName, operation, result);
handleError<T> (serviceName = '', operation = 'operation', result = {} as T ){
return (error: HttpErrorResponse): Observable<T> => {
const message = (error.error instanceof ErrorEvent) ? error.error.message: `{error code: ${error.status}, body: "${error.message}"}`;
this.errorService.errorMessage = `${serviceName} -> ${operation} failed.\n Message: ${message}`;
console.error(this.errorService.errorMessage);
return of(result);
}
}
}
这是我如何在组件中调用服务删除函数的示例:
this.service.delete(nom).subscribe(data => {
if(!this.errorService.errorMessage){
this.notificationService.success("Suppression", "L'enregistrement a été supprimée !");
}
});
但在我的情况下指定 observe: "response" 不起作用,error: HttpErrorResponse 只返回错误消息而不是完整响应:
我在这个帖子中尝试了解决方案:Angular 4.3.3 HttpClient : How get value from the header of a response? 这对我不起作用,提供的解决方案是定义观察选项。
我该如何解决这个问题?
更新:
仅当删除http请求返回200代码时,观察选项才有效,如下图所示,但是当有404响应状态时,这种情况下的响应对象为空,并且在handleError函数中响应正文为我唯一可以访问的东西。
【问题讨论】:
-
我试图在堆栈闪电战中复制您的问题,但我得到了作为 HttpErrorResponse 的完整错误响应,因为它应该是:stackblitz.com/edit/angular-hh4x4z 我不太确定您的问题是什么。请您自己提供一个堆栈闪电战,展示您的错误和您遇到的问题!
标签: angular error-handling rxjs