我正在尝试在Angular 2中调用HTTP Post方法来检索PDF文件,因此我将ResponseContentType设置为Blob,如下所示:
let headers = new Headers({
'Content-Type': 'application/json',
'ApplicationName': 'ControlEnroll',
'Accept': 'application/pdf'
});
let options = new RequestOptions({
headers: headers,
responseType: ResponseContentType.Blob
});
现在,我对post()
调用成功的时间没有问题,但是当它出错时,我在解决从WebAPI方法返回的错误消息方面遇到问题,因为它包含在Blob中
由于这是Angular 2,我的post()
调用和结构现在看起来像这样:
return this.http.post(postUrl, {
// ... some body parameters here ...
}, options)
.map(resp => {
let blob: Blob = resp.blob();
// Use the file-save library to persist this to disk.
window['saveAs'](blob, 'File.pdf');
return resp;
}).catch(error => {
// What to do?
});
问题在于catch()
方法,我知道提供的error
是一个包含Blob体的Response对象。从我知道的Blob对象中提取文本的唯一方法是使用FileReader和事件监听器,如下所示:
let body = error.json();
let reader = new FileReader();
reader.addEventListener('loadend', function () {
console.log(reader.result);
});
reader.readAsText(body);
然而,这不会立即发生;这是一个事件倾听者。然而,catch()
必须[likey] throw
对外部的某种错误是可观察的,对吧?如何处理这个catch()
方法,让我将字符串从Blob中拉出来,然后允许其他人订阅整个方法并使用普通的subscribe(successFn, errorFn)
结构?有可能吗?
答案 0 :(得分:0)
传递给catch
运算符的选择器函数可以返回一个observable,用于在发生错误时继续观察链。
因此,您的选择器函数可以返回一个observable,它等待来自loadend
的{{1}}事件,然后使用您从BLOB读取的消息抛出错误。像这样:
FileReader