![](/img/trans.png)
[英]How to call an http method without the observable in Angular 2
[英]Angular Multiple Http Call grouping error to parent observable method
我有一个关于多个 http 调用以及在它们发生时捕获错误并能够在父组件上读取它们的问题。 我需要知道哪些调用失败了,以便我可以在另一种方法上重试它们,但是如果我在组件级别看不到它们,不知何故我不可能知道我需要重试哪个调用
// 组件调用
generateDocuments(documentType: DocumentType, validDocuments: DocumentTemplate): observable<any>{
return this.documentService.generateDocuments(clientId, ClientDescription,documentType, validDocuments)}
//服务调用:
generateDocuments(clientId: int, ClientDescription,documentType:DocumentType, validDocuments: DocumentTemplate): observable<any>{
switch(documentType){
documentType.Word:{
return this.getDocumentCall(clientId, ClientDescription, ...)}
documentType.Excel:{
return this.getDocumentCall(clientId, ClientDescription, ...)}
}
// 此行将根据调用完成的时间一一抛出错误/成功
private getDocumentCall(clientId: int, clientDescription: string, ....)
{
return forkjoin([1,2,4,4,5].map((documentId:number) => {
this.http.get('uri'+documentId+'/'+clientId,headers..).pipe( catchError(error => {
return of(error);
});
});
我的问题是如何知道组件级别的调用成功或失败,或者能够将所有错误/响应冒泡到组件级别
谢谢
在这里查看forkJoin
。 我认为对你来说最好传递一个带有键值对的 object,这样你就可以更好地识别。
您拥有它的方式,订阅时订阅每个调用时的顺序将相同(本质上它仍将在 [1, 2, 3, 4, 5] 中)。
您的catchError
捕获 API 调用的错误并为subscribes
返回成功的错误 object 。
这样的事情应该让你开始:
this.service.getDocumentCall(1, 'hello').subscribe(responses => {
responses.forEach(response => {
// check if the response is instance of HttpErrorResponse signalling an error
if (response instanceof HttpErrorResponse) {
console.log('This call failed');
} else {
console.log('This call succeeded');
}
});
});
编辑:
尝试这样的事情:
private getDocumentCall(clientId: int, clientDescription: string, ....)
{
const calls = {};
const ids = [1, 2, 3, 4, 5];
// create the calls object
ids.forEach(id => {
calls[id] = this.http.get('uri' + id + '/' + clientId, headers...).pipe( catchError(error => {
return of(error);
});
});
return forkJoin(calls);
});
this.getDocumentCall(1, '2').subscribe(response => {
// loop through object
for (const key in response) {
if (response[key] instanceof HttpErrorResponse) {
console.log(`Call with id: ${key} failed`);
} else {
console.log(`Call with id: ${key} succeeded`);
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.