In Angular, make a call to a second API if the first API call times out after a specified period

In the event that my API does not return data within 5 seconds, I need to call a different one. Attempted implementation:

this.service.returnData1(param1, param2)
.pipe(timeout(5000), finalize(() => this.callSecondApi()))
.subscribe(
  data => {
    this.myList = data.filter(item => !this.removeStuffFromList(item, data));
    if (this.myList.length > 0) {
      //perform additional tasks
      this.originalList = this.myList;
    }
  },
  (err) => {
    console.log(err.message);
  }
 )

callSecondApi(){
this.service.returnData2(param1, param2).subscribe(
   data1 => {
        this.myList = data1.filter(item => !this.removeStuffFromList(item, data1));
        }
        if (this.myList.length > 0) {
           this.originalList = this.myList;
        }
      },
      (err) => console.log(err.message)
   )
  }

What is the most effective approach for resolving this issue? Tried various solutions involving switchMap, tap, mergeMap, but none worked due to the necessity of adding a timeout to the first subscribe operation. Thank you!

Answer №1

To ensure a smooth transition to observing the second API call only after the first one has failed or timed out, avoid using finalize and opt for the catchError operator instead:

this.service
  .returnData1('param1', 'param2')
  .pipe(
    timeout(5000),
    catchError((err) => callSecondApi())
  )
  .subscribe({
    next: (data) => {
      console.log(data);
    },
    error: (err) => {
      console.log(err.message);
    },
  });

Note: It is recommended to utilize an observer object rather than passing separate functions to a subscribe call.

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

Styling Angular Material Forms: Customizing Input Backgrounds and Button Heights

I'm currently working on a simple email input form with a submit button. Here are the adjustments I want to make: Set the background of the email input to white Ensure that the submit button matches the height of the input field However, my attempts ...

Angular StrictNullChecks: "Error - object may be null"

I am encountering an issue with the 'strictNullChecks' setting in my Angular project. This has resulted in numerous errors across my templates (.html), such as: <input #inputValue type="text" (keyup.ent ...

The onChange event will not be triggered in an input component that is not intended to be uncontrolled

Could someone please assist me in understanding why the onChange event is not being triggered? I am customizing ChakraUI's Input component to retrieve a value from localStorage if it exists. The component successfully retrieves the value from localS ...

Oops! An issue occurred while trying to compile the file constructor.d.ts in the common-behaviors folder of @angular/material/core. The error message received was: "error TS1005: ';'

Switching from Bootstrap to Angular Material caused an unexpected error when trying to run ng serve: Error: node_modules/@angular/material/core/common-behaviors/constructor.d.ts:14:64 - error TS1005: ';' expected. The errors encountered include: ...

Interactive mat-select within Angular material table

I have retrieved data from an endpoint and displaying it in a material table. However, I also have an additional column requestedStatus, which contains a mat-select with 2 options. I want the selected option to dynamically update the row by adding a new ke ...

Eratosthenes' Sieve with the Power of Forking

I'm currently working on a C code that takes a text file as input. Each line in the text file contains numbers in increasing order from 2 to N, and my goal is to identify prime numbers using the Sieve of Eratosthenes algorithm. I plan to utilize Fork( ...

Find out whether the page was reloaded or accessed directly through a hyperlink

I need to find out if the page was accessed directly via a link. If it was, I need to perform a certain action. However, my current implementation is not working as intended, as even a page refresh triggers this action. Is there an alternative method to ch ...

Validation of Date in Angular 5 (with specified minimum and maximum dates)

Struggling to find a simple solution for this issue, I have a date input like the following: <input [(ngModel)]="toolDate" type="text" class="tool_input tool_input__date"> To control the input and restrict it to only accept dates, I am using . In m ...

Troubleshooting: Issue with Angular 2 bidirectional data binding on two input fields

Hi there, I am encountering an issue with the following code snippet: <input type="radio" value="{{commencementDate.value}}" id="bankCommencementDateSelect" formControlName="bankCommencementDate"> <input #commencementDate id="bankCommencementDat ...

Tracking code execution in React, Enzyme, and Istanbul reveals uncovered functions running during tests

I have been working on testing a React component that involves 3 functions. The tests I've written for these functions pass successfully, but my code coverage report indicates only a 33% coverage. Here is the code snippet of the component: const AddW ...

Rotate object within HTML table

I have a simple data structure as shown below: [ { "ClientId": 512, "ProductId": 7779, "Date": "2019-01-01", "Quantity": 20.5, "Value": 10.5 }, { "ClientId": 512, "ProductId": ...

Integrating Paytm with Angular 6: A Step-by-

I am currently facing an issue where I am not being redirected to the paytm server's page after using the HTML form for integrating paytm in PHP. Can anyone provide assistance with this matter? ...

FormArray in reactive forms with draggable formGroups

Within the angular drag-drop module, there is documentation available for the moveItemInArray() function which allows dragging content within an array. However, how can we shuffle (formGroups/formControls) in formArray? I attempted to use the moveItemInFo ...

Sharing events between disparate components in Angular

Is there a way in Angular to trigger an event within one component and then have another completely unrelated component listen for that event? These components do not share a parent or have any sort of parent-child relationship. I'm trying to find a s ...

TypeScript is throwing an error about a missing property, even though it has been defined

Within the PianoMK1Props component, there is a prop known as recording which accepts an object with specific properties. The structure of this object is defined like so(the state variable): const [recording, setRecording] = useState({ mode: "REC ...

Tips for minimizing the amount of code in Angular 5

As our Angular 5 application continues to expand, due to being a Single Page Application with dynamic components, our main component is becoming overloaded. The main component is responsible for rendering other components and contains the majority of the l ...

What is the best way to wait for a series of subscriptions to complete?

I am currently facing challenges with Observables while working on a complex REST API query function that involves intricate logic and multiple requests and responses. Although I have already written numerous functions with subscriptions like the ones bel ...

Jasmine has detected an undefined dependency

Testing out the following code: constructor(drawingService: DrawingService) { super(drawingService); //... } private writeOnCanvas(): void { this.drawingService.clearCanvas(this.drawingService.previewCtx); this.drawing ...

Can Angular access a JSON file post-build?

Currently, I am developing an Angular 7 project that has to be deployed on various servers. One of the requirements is to retrieve the server URL from an environment file rather than hardcoding it as a static variable. I attempted to read the information ...

Prisma Remix is throwing a TypeError: "The function (0, import_prisma.createNote) is not defined as a function."

In my project, I wrote a function using the prisma client which is being called from the notes.tsx route in remix. export async function createNote(entity: { title: string, description: string }) { const note = await prisma.note.create({ data: ...