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

The PrimeNG table fails to refresh upon initial modification

I'm working with a prime-ng table of shops, where I have the ability to remove and add shops to a list. The scenario: Whenever a shop is added, the ChildComponent emits an event to the ParentComponent, which then adds the shop to the list and updates ...

Is there a way for me to convert my (TypeScript Definition) .d.ts file into a (JavaScript) .js file?

It seems that there are plenty of guides available on converting a file from .js to .d.ts, but not the other way around. Specifically, I have some code in .d.ts format and I would like to convert it into JavaScript. Can anyone offer assistance with this t ...

Error: Unable to access the 'filter' property as it is undefined. TypeError occurred

findLoads(){ if(this.loggedInUser.userFullySetupFlag === 0 || this.loggedInUser.businessFullySetupFlag === 0){ swal( 'Incomplete Profile', 'To find loads and bid, all the details inside User Profile (My Profile) and Business Profil ...

It is possible that the object may be null, as indicated by TS2531 error

I was interested in using QrReader to scan a file based on [https://github.com/Musawirkhann/react_qrcode_generation_scanner This code is written in react, but I wanted to use it with tsx. However, when attempting to implement it, I encountered an error: ...

When using the RxJs Pipe with MAP in Angular and Ionic, it may not return a value in windows, but it works perfectly in Mac when used with HttpClient

I'm currently using RxJs Pipe with Map for a network request in my Angular/Ionic project. Interestingly, while I do receive a successful response in the network log, the MAP function fails to return any value. Notable Observations Strangely, this fu ...

How can you dynamically disable a radio option button using Angular rendering without relying on an ID?

Is there a way to disable the male radio button without using an id, and utilizing angular rendering2? It seems like it's not working for me. I need to make this change only in the form.ts file, without altering the HTML code. form.html <label& ...

Angular 4 with Universal: Implementing 404 Status Code in Header for /404 Page Component

After researching and reviewing numerous StackOverflow inquiries, I have come to the conclusion that headers are derived from responses served by servers, making it a non-issue. I attempted to rectify the situation from my server.ts file but unfortunately ...

The RxJS race function comes to a standstill if neither stream completes

Consider the code snippet below: import { interval, race, Subject } from 'rxjs'; import { mapTo } from 'rxjs/operators'; const a$ = new Subject<number>(); const b$ = interval(1000).pipe(mapTo(1)); race([a$, b$]).subscribe(consol ...

Discover the potential of JavaScript's match object and unleash its power through

In the given data source, there is a key called 'isEdit' which has a boolean value. The column value in the data source matches the keys in the tempValues. After comparison, we check if the value of 'isEdit' from the data source is true ...

Is there a TypeScript rule called "no-function-constructor-with-string-args" that needs an example?

The description provided at this link is concise: Avoid using the Function constructor with a string argument to define the function body This might also apply to the rule missing-optional-annotation: A parameter that comes after one or more optiona ...

Error: Protractor encountered an unexpected token while trying to import an external class

While working on my Protractor test, I encountered a syntax error on import when trying to bring an external class into the test. The strange thing is that the error only occurs at runtime, even though I am confident that I am importing and exporting the c ...

The external typing file encounters an issue when trying to locate the relative path to its own index.d.ts file

While working on my project and using react-color as a dependency, I encountered an issue with the tsc import failing. The error message displayed: node_modules/@types/react-color/lib/components/sketch/Sketch.d.ts(2,41): error TS2307: Cannot find module & ...

Configuring Angular for Seamless Integration with a Backend API in Kubernetes Environment

Two separate containers, Auth and Frontend, are currently functioning independently. The next step is to establish a connection between the two in order to send and receive HTTP requests. In Angular, connections are typically made using URLs like http://l ...

Break down a data structure into a type that includes multiple options

Is it possible for Typescript to support type or interface "destructuring" (if that's the right term)? I am attempting to achieve something similar to the code snippet below: type SomeRandomType = { propertyOne: string; propertyTwo: number; ...

Can you explain the distinction between rxjs/observable and the traditional jQuery AJAX approach?

Can you explain the distinction between rxjs/Observables and JQuery in terms of asynchronous functions like $.get()? Are both frameworks considered to be asynchronous and reactive? ...

Exploring Angular 2 Paper-Input for Effective Form Management

I've been working on implementing Ng2 FormBuilder with paper-inputs and have successfully managed to get the bindings and validation up and running. You can check out my progress here: https://plnkr.co/edit/tr1wYZFyrn4uAzssn5Zs?p=preview <paper-i ...

What is the best method for installing the most recent 1.1.5 version of is-callable?

After running the command npm install, an error occurred: npm ERR! code ETARGET npm ERR! notarget No matching version found for is-callable@^1.1.5. npm ERR! notarget In most cases you or one of your dependencies are requesting npm ERR! notarget a ...

Bidirectional Binding of Angular HTML Fields in Quill Editor

Is there a way to incorporate HTML fields into Quill? I am looking to have numeric fields integrated within the text, and use two-way Angular binding. When trying to bind to the model, Quill seems to be removing my input fields. this.myValue = 5; this.m ...

Retrieving child elements from parent identifiers using Typescript

I've been working on creating a new array with children from the data fetched from my database. While my initial attempt was somewhat successful, I believe there are some missing pieces. Could you assist me with this? Here is the raw data retrieved f ...

Issue with Object.keys printing in an abnormal manner

My goal is to extract only the keys from an object, but instead of getting the desired output with the keys, I am seeing numbers. Here is the code snippet: data = {"property" : "{\"animalID\": \"12345\" ...