2016-08-24 50 views
8

我试图在Angular 2 RC 5项目中显示从服务器生成的视图到视图中的PDF。现在,ASPNETCORE服务器正在以'application/pdf'的形式返回对象,并且Angular客户端试图将响应解析为一个blob。不过,我得到以下错误在客户端:Angular 2 RC 5试图从服务器获取并显示PDF

Error: The request body isn't either a blob or an array buffer

,我使用调用PDF服务器的代码基本上是:

getHeaders() : Headers { 
    var headers = new Headers({ 
     'responseType': 'application/blob' 
    }); 
    return headers; 
} 

getBlob() { 
    return this.http.get(uri, new RequestOptions({headers: this.getHeaders()}, body: "" })) 
    .map(response => (<Response>response).blob()); 
} 

回答

17

尝试设置的responseType到BLOB ,它应该工作:

getBlob() { 
return this.http.get(uri, {responseType: ResponseContentType.Blob}) 
.map(response => (<Response>response).blob()); 

}

+1

这是 '现代' 的答案。在RC5上工作 – reflog

+0

当我尝试打开保存的文件时,出现关于破坏数据的错误 –

+0

这使请求熄灭并得到响应,但将响应作为Blob返回,但没有明显的方式来获取响应的文本 – ShadSterling

1

工作中的F或者我:

组件:

downloadInvoice(invoice) { 
    this.loading = true; 
    this.invoiceDataService 
    .downloadInvoice(invoice) 
    .subscribe(
    (blob) => { 
     FileSaver.saveAs(blob, 'test.pdf'); 
    }, 
    error => this.error = error, 
    () => { 
     this.loading = false; 
     console.log('downloadInvoices : Request Complete') 
    } 
) 
} 

数据服务:

downloadInvoice(invoice): Observable<Blob> { 
    return this.api.downloadInvoice(invoice); 
} 

API服务:

downloadInvoice(invoice: Invoice): Observable<Blob> { 
    return this.authHttp 
    .get(this.apiBase + '/invoices/' + invoice.hashid + '/download', {responseType: ResponseContentType.Blob}) 
    .map(response => { 
    return new Blob([response.blob()], {type: 'application/pdf'}); 
    }) 
    .catch(this.handleError.bind(this)); 
} 

享受:)

相关问题