在角度文档中,他们指出您必须指定
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))
);
}
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 !");
}
});
注意:“回应”
在我的情况下不起作用,而且
error: HttpErrorResponse
我已经尝试过这方面的解决方案:
Angular 4.3.3 HttpClient : How get value from the header of a response?
这对我不起作用,提供的解决方案是定义observe选项。
我怎样才能解决这个问题?
“观察”选项仅在删除http请求返回200代码时有效,如下面的屏幕截图所示,但当存在404响应状态时,本例中的响应对象为null,在handleError函数中,响应主体是我唯一可以访问的对象。