问题描述
我有一个关于多个 http 调用和在错误发生时捕获错误以及能够在父组件上读取它们的问题。 我需要知道哪些调用失败了,以便我可以在另一种方法上重试它们,但是如果我在组件级别看不到它们,不知何故我无法知道我需要重试哪个调用
// 组件调用
generateDocuments(documentType: DocumentType,validDocuments: DocumentTemplate): observable<any>{
return this.documentService.generateDocuments(clientId,ClientDescription,documentType,validDocuments)}
//服务调用:
generateDocuments(clientId: int,documentType:DocumentType,validDocuments: DocumentTemplate): observable<any>{
switch(documentType){
documentType.Word:{
return this.getDocumentCall(clientId,...)}
documentType.Excel:{
return this.getDocumentCall(clientId,...)}
}
private getDocumentCall(clientId: int,clientDescription: string,....)
{
return forkjoin([1,2,4,5].map((documentId:number) => {
this.http.get('uri'+documentId+'/'+clientId,headers..).pipe( catchError(error => {
return of(error);
});
});
我的问题是如何知道组件级别的调用成功或失败,或者能够将所有错误/响应冒泡到组件级别
谢谢
解决方法
查看 forkJoin
here。我觉得对你来说最好传入一个带有键值对的对象,这样你可以更好地识别。
按照你的方式,订阅时每次调用的顺序都是一样的(本质上它仍然是 [1,2,3,4,5])。
您的 catchError
捕获 API 调用的错误,并为 subscribes
的任何人返回一个成功的错误对象。
这样的事情应该会让你开始:
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,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`);
}
}
});