使用reponseType Blob Angular 4处理错误

时间:2017-09-25 17:37:11

标签: angular http rxjs

当我需要处理来自pdf http请求的错误时出错。 这是我的pdf(实名改变)的服务方法:

generateSomePdf(obj: any): Observable<any> {
  const headers = new Headers();
  const options = new RequestOptions();
  const url = 'http://localhost:8080/api/v1/pdf/print';

  headers.append('Content-Type', 'application/json')
  headers.append('Accept', 'application/pdf');
  options.headers = headers;

  return this.http.post(url, obj, {responseType: ResponseContentType.Blob})
    .map(res => {
      let blob = new Blob([res.blob()], {type: 'application/pdf'});
      return blob;
    })
    .catch(this.handleError);
}

错误的句柄是这样的:

handleError(error: Response | any) {
  let errMsg: string;

  if (error instanceof Response) {
    const body = error.json() || '';
    let err;

    if (body.errors != null) {
      err = body.errors || JSON.stringify(body);
    } else {
      err = body.error || JSON.stringify(body);
    }

    errMsg = `${err}`;
    console.error(`${error.status} - ${error.statusText || ''} ${err}`);
  } else {
    errMsg = error.message ? error.message : error.toString();
  }
  console.error(errMsg);
  return Observable.throw(errMsg);
}

因此,当我收到此帖子的后端响应时,pdf工作正常,但是当我收到一些错误时,Angular的处理程序获取Blob而不是从后端返回的json。那我怎么办呢?

当我没有设置responseType时,错误正常,但pdf没有生成。

1 个答案:

答案 0 :(得分:-1)

getPDF() {
    return this.http.get(`${environment.baseUrl}/api/v.1/reports/...`, { responseType: ResponseContentType.Blob })
      .map((res) => {
        return {
          blob: new Blob([res.blob()], { type: 'application/pdf' }), filename: this.parseFilename(res)
        }
      })
      .catch((res) => {
        let fileAsTextObservable = new Observable<string>(observer => {
          const reader = new FileReader();
          reader.onload = (e) => {
            let responseText = (<any>e.target).result;

            observer.next(responseText);
            observer.complete();
          }
          const errMsg = reader.readAsText(res.blob(), 'utf-8');
        });

        return fileAsTextObservable
          .switchMap(errMsgJsonAsText => {
            return Observable.throw(JSON.parse(errMsgJsonAsText));
          })
      });
  }