Angular 服务错误处理responseType = blob

问题描述 投票:0回答:1

我正在处理 Angular 服务中的错误(我有下载文件的方法,但在错误期间我返回带有错误文本的 json)。

FileService
方法:

downloadRaw(id: string, revision: number = 0): Observable<HttpResponse<Blob> | JsonError> {
    let params = new HttpParams();
    params = params.set('revision', revision.toString());

    return this.http
      .get(this.downloadRawFileUrl
        .replace(':id', id),
        {
          observe: 'response',
          responseType: 'blob',
          params: params 
        })
      .pipe(
        catchError(this.errorService.handleError)
      );
  }

成分方法:

downloadFile(fileGUID: string) {
    this.fileService.downloadRaw(fileGUID).subscribe(
      (response: (HttpResponse<Blob> | JsonError)) => {
        if ((<JsonError>response).errors == undefined) {
          let fileName = (<HttpResponse<Blob>>response).headers.get('File-Name');
          const downloadURL = URL.createObjectURL(<Blob>(<HttpResponse<Blob>>response).body);
          const link = document.createElement('a');
          link.href = downloadURL;
          link.download = <string>fileName;
          link.click();
          URL.revokeObjectURL(downloadURL);
        }
      }
    );
  }

这是我的

ErrorService

export class ErrorService {
    constructor(private toastr: ToastrService) { }

    handleError(error: HttpErrorResponse): Observable<JsonError> {
        let jsonError: JsonError = new JsonError();
        if(error.error instanceof Blob) {
            this.getJsonError(error).then((response: JsonError) => {
                jsonError = response;
                this.showToastr(jsonError);
                return of(response);
            });
        } else {
            jsonError = error.error;
            this.showToastr(jsonError);
        }
        
        return of(jsonError);
    }

    getJsonError(error: HttpErrorResponse): Promise<JsonError> {
        return error.error.text().then((text: string) => {
            let jsonError = JSON.parse(text);
            return jsonError;
        });
    }

    showToastr(jsonError: JsonError): void {
        for (const er of jsonError.errors) {
            this.toastr.error(er.message, er.title);
        }
    }
}

我有错误:

ERROR TypeError: Cannot read properties of undefined (reading 'getJsonError')
进入组件这行代码:

this.fileService.downloadRaw(fileGUID).subscribe(

也许退货类型有误? 我究竟做错了什么?也许我怎样才能简化这项服务?

angular error-handling
1个回答
0
投票

改变调用错误服务方法的方式:

catchError(error=>this.errorService.handleError(error))
© www.soinside.com 2019 - 2024. All rights reserved.