Parent observable method encountering an error while grouping multiple HTTP calls in Angular

I am facing an issue with managing multiple http calls and handling errors that may occur during their execution. I want to be able to identify which calls have failed so that I can retry them using a different method. However, without visibility at the component level, it becomes challenging for me to determine which specific call needs to be retried.

// 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);
              });
    });

I am looking for a way to track successful or failed calls at the component level, or find a method to bubble up all errors/responses to the component level for better management.

Thank you

Answer №1

Explore the forkJoin function here. Consider passing in an object with key-value pairs for better identification in your case.

As it is currently set up, the order will remain the same for each subscription (resulting in [1, 2, 3, 4, 5] every time).

Your catchError method handles errors from API calls and returns a successful error object to subscribers.

To start off, you can try something like this:

this.service.getDocumentCall(1, 'hello').subscribe(responses => {
  responses.forEach(response => {
     if (response instanceof HttpErrorResponse) {
        console.log('This call failed');
     } else {
        console.log('This call succeeded');
     }
  });
});

Edit:

You may want to consider implementing something along these lines:

private getDocumentCall(clientId: int, clientDescription: string, ....)
    {
      const calls = {};
      const ids = [1, 2, 3, 4, 5];
      
      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 => {
  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`);
    }
  }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to showcase the chosen information?

Typically, I maintain a list of specific entries within cards. When clicking on one of the records in the card, the corresponding data table is supposed to be displayed below that record. An issue arises where after selecting a record and displaying its d ...

While utilizing Typescript, it is unable to identify changes made to a property by a

Here is a snippet of code I am working with: class A { constructor(private num: number = 1) { } private changeNum() { this.num = Math.random(); } private fn() { if(this.num == 1) { this.changeNum(); if(this.num == 0.5) { ...

Turn off the button and add a CSS class to it when sending a message

I have an Angular 7 component with a form that includes the following TypeScript code: export class MessageComponent implements OnInit { message: FormGroup; constructor(private formBuilder: FormBuilder, private messageService: MessageService) { } ...

What could be the reason behind the malfunction of nativescript-phone on Android during plugin build?

I am encountering a particular build error while trying to deploy our NativeScript app on my Android Studio Emulator: > Failed to build plugin nativescript-phone : Error: spawn ./gradlew ENOENT Exception in thread "DisconnectableInputStream source ...

What steps should I follow to create a versatile table component?

Can you please advise me on how to create generic data in a table using Typescript? I encountered this error message while trying to useTable({ at line data The error states: Type 'T[]' is not assignable to type 'readonly object[]'. ...

Can you explain how to invoke a class with express().use function?

Currently, I am delving into learning Node JS with TypeScript but have hit a roadblock with a particular issue. In my app.ts file, I have initialized the express and attempted to call the router class inside the app.use() method, only to encounter an error ...

What is the best way to get both the id and name of a selected item in Angular?

Within my select field, data is dynamically populated based on names. My objective is to not only capture the selected name but also its corresponding ID. Here's a snippet of my HTML template: <select class="custom-select d-block w-100" id="test" ...

Switch back and forth between two pages within the same tab on an Ionic 3 app depending on the user's login information

I am seeking a way to switch between two profile pages using the profile tab based on whether the user is a student or tutor in an ionic 3 application. ...

Icon appearing outside the button instead of inside

Here's a button I'm working with: <button class="glyphicon glyphicon-option-horizontal" (click)="myFuncion()"></button> Recently, I updated my bootstrap library from version 3 to 4.2.1 and now the icon is no longer visible. I' ...

Ways to obtain the present value in Angular

Hello, I am looking for assistance in displaying Toast notifications on my View whenever the number of notifications increases (i.e., when new data is added to the database). I have attempted to use this function, but I am unsure how to retrieve the curre ...

Update Observable by assigning it a new value of transformed information using the async pipe and RXJS

My service always returns data in the form of Observable<T>, and unfortunately, I am unable to modify this service. I have a button that triggers a method call to the service whenever it is clicked. This action results in a new Observable being retu ...

Error in Mongoose Schema Configuration Detected in NestJS App

I'm currently developing an e-commerce application using NestJS and MongoDB with Mongoose. I've been facing an issue while trying to implement a user's shopping cart in the application. The error message I keep encountering is as follows: ...

Mixing Jest and Cypress in a TypeScript environment can lead to Assertion and JestMatchers issues

When utilizing [email protected] alongside Jest, we are encountering TypeScript errors related to Assertion and JestMatchers. What is the reason for these TypeScript errors when using Jest and [email protected] in the same project? ...

Sending information from the AppComponent to another component that is loaded at a separate time

Is there a way for me to maximize efficiency when fetching data from a service in the AppComponent and then passing it on to another component that's loaded later? I'd like to minimize API calls by reusing the same data in multiple places. How ca ...

Ways to customize the appearance of Angular material elements one by one?

I have a component that contains two Angular Material form components: <!-- First input --> <mat-form-field> <mat-label>Password</mat-label> <input matInput type="text"> </mat-form-field> <br&g ...

Error TS2532 in TypeScript indicates that there is a possibility that the object is undefined

Yesterday, WebStorm 2020.1 was installed on my computer. All of a sudden, I started encountering numerous TS2532 errors. How is it even possible for this to be "undefined"? Doesn't selectedOwner && prevent that? I attempted to eliminate thi ...

Implementing Angular - Injecting a component dynamically into another component

Currently, I am working on developing a small UI components framework for my personal use and enjoyment. One of the components I'm working on is a Tab component. To test this component, I need to dynamically inject another component (TabContainerCompo ...

What are the methods to determine the cause of ESLint's slow performance?

Looking to analyze the performance of ESLint in my application. So far, I have only come across one profiling tool provided by ESLint which is the TIMING=1 environment variable. Combining this with DEBUG=eslint:cli-engine allows me to see timing results pe ...

Using the --prod flag in Ionic 3 app on Android 7 results in the Keyboard not being displayed

After running the command ionic cordova run android --device, everything functions properly. However, when attempting the same command with the --prod flag, the input click fails to display the keyboard despite implementing the (onFocus) attribute in the & ...

Oops! It seems like there was an issue trying to access properties that are undefined while reading 'pipe' in Angular12

I encountered an issue when trying to send an AJAX request, displaying the following error message: ERROR TypeError: Cannot read properties of undefined (reading 'pipe') This error occurred in the ajax-loader.interceptor.ts class export class A ...