I have a question regarding multiple http calls and catching errors when they happen and be able to read them on a parent component. I need to know which calls failed so that I can retry them on another method but if I can't see them on component level It is somehow impossibe for me to know which call I need to retry
// COMPONENT CALL
generateDocuments(documentType: DocumentType, validDocuments: DocumentTemplate): observable<any>{
return this.documentService.generateDocuments(clientId, ClientDescription,documentType, validDocuments)}
//SERVICE CALL:
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, ...)}
}
// This line will throw an error/success one by one depending on when the call complete
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);
});
});
my question is how can I know what call succeeded or failed at component level, or be able to bubble all errors/response to component level
Thanks
Check out forkJoin
here . I think for you it is better to pass in an object with key value pairs so you can make better identification.
The way you have it, the order will be the same when subscribed for every call (in essence it will still be in [1, 2, 3, 4, 5]) when subscribed.
Your catchError
catches errors for the API call and returns a successful error object for whoever subscribes
.
Something like this should get you started:
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');
}
});
});
Edit:
Try something like this:
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`);
}
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.