Angular http.get() recognizing when a call exceeds its timeout limit

I'm currently facing a challenge in detecting request timeouts with Angular http and promises. My code is designed to format API responses, but it fails to handle timeout errors effectively. Despite working when the API returns an error message, it does not respond when the API times out.

My search for documentation on handling timeouts in Angular http has been fruitless so far. Any guidance or solutions would be greatly appreciated, thank you!

Here's the relevant code snippet:

/**
  * GET from the API
  * @param params  What to send
  * @param path    Where to go
  */
public get(path, params): Promise<any> {
  return this.formatResponse(
    this.http.get(this.apiUrl + path, params)
  );
}

/**
  * Takes the API response and converts it to something usable
  * @param response Promise of formatted data
  */
public formatResponse(response): Promise<any> {
  return response
    .toPromise()
    .then(r => r.json().data)
    .catch(e => {
      console.log('hitting error');
      const errors = e.json().errors;
      let error = 'Something went wrong, please try again in a few minutes.';

      if (errors && errors.length > 0) {
        error = errors[0].message;
      }

      // Create alert
      this.utilities.createAlert(
        'Whoops!',
        error
      );

      // Throw the error
      throw new Error(error);
    });
}

Observing the network tab, I notice the following message:

Failed to load resource: The request timed out.

Answer №1

what do you think of this

function fetch(url, options): Promise<any> {
  return formatData(
    sendRequest(backendUrl + url, options).pipe(timeout(10000), catchError(handleErrors)
  );
}

Feel free to customize the error handler as needed. The remaining code remains unchanged.

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

Guide on how to modify a static css file using Node.js

Issue Whenever a user updates the theme on the front-end, my Node.js API needs to update the static CSS file located in a public folder set up by Express. This way, when pages are served again with <link href="public/theme.[userId].[hash].css", the use ...

Node.js Express.js Module for Asynchronous SqLite Operations

Currently, I am working on a task that involves making synchronous requests to a database and passing the data to Express. Here is the code snippet: app.get('/', (req, res) => { let db = new sqlite3.Database('./Problems.db'); ...

Issue with Vue 3: defineAsyncComponent is not able to resolve .vue files or split chunks properly

I'm currently attempting to dynamically load Vue 3 components in an asynchronous manner. I have come across a function called defineAsyncComponent which is intended to be utilized as shown below: const GameUI = defineAsyncComponent(()=>import(file ...

Getting the URL path within getStaticPaths in Next.js

Is there a way to retrieve the last number from the current URL pathnames in getStaticPaths? http://localhost:3000/category/food/2 -> 2, http://localhost:3000/category/food/3 -> 3, ... I have attempted: export const getStaticPaths: GetStaticPaths = ...

Error message: The specified file or directory does not exist and cannot be unlinked

fs.unlink('backup/' + 'test') An issue arises when attempting to delete a folder: { [Error: ENOENT: no such file or directory, unlink 'backup/test'] errno: -2, code: 'ENOENT', syscall: 'unlink', p ...

The asynchronous ajax request is leading to a browser freeze

In the HTML page, I have two sets of a and p elements that are initially set to display:none. At the bottom of the page, there is a function being called with their respective ID's and values, which will enable one of them based on certain conditions ...

When using Next.js and Express.js together, CORS error may occur, causing API queries to only function properly during build

I am currently working on a project that involves using Next.js for the front-end and Express.js for the back-end. Front-end Setup The 'pages' directory contains an 'index.js' file where I have implemented the following code snippet: ...

Adding elements to an array using Angular observables

I have been using this code snippet to store task names in my array barChartLabels. public lineChartLabels: Label[] = []; this.tasks.pipe(map(x => x.map(x => x.id))).toPromise().then(id => this.lineChartLabels.push(id)) The code is functionally ...

Monitor the completion of the scrollTo action

My webpage contains a scrollable element. Additionally, I have a function in place that allows me to scroll to a specific position within this element. Now, I am looking for a way to trigger another function once the scrolling action is completed. Check o ...

Organizing methods to manage changes in universal and specific states

There are certain components in my application that do not need to store all their state globally. Let me provide you with two examples: messages component: User messages are fetched and stored locally because they are only required for the current compo ...

When state is updated, the component is re-rendered multiple times

I am working on setting the state in componentDidMount lifecycle method to verify data from local storage. Depending on whether the data exists in local storage, I either redirect the user to the login page or keep them on the dashboard. Is there a way to ...

Switch up row values in an array and transform them into an object using SheetJS

I am struggling to format an array where each "Working Day" is represented as an object with specific details like index and start/end date. I need help manipulating the JSON data to achieve the desired structure. The package I'm currently using is: ...

Troubleshooting JSONP Implementation with JQuery: Scope versus Async Problems

I've been trying to call a JSONP service using the $.ajax function: $.ajax({ url: jsonpURI, dataType: "jsonp", jsonpCallback: callback, success: function () { console.log("Success"); }, error: function (err) { ...

Stuck on loading screen with Angular 2 Testing App

Currently working on creating a test app for Angular 2, but encountering an issue where my application is continuously stuck on the "Loading..." screen. Below are the various files involved: app.component.ts: import {Component} from '@angular/core& ...

Exploring Mixed Type Arrays Initialization in Typescript using Class-Transformer Library

In my class, I have a property member that is of type array. Each item in the array can be of various types such as MetaViewDatalinked or MetaViewContainer, as shown below class MetaViewContainer{ children: (MetaViewDatalinked | MetaViewContainer)[]; ...

Is it possible to activate a click event on a v-select component?

I am currently using vue-select and I would like to create a click event when an item is selected from the select list. I attempted to use @change="changedValue" @selected="changedLabel" but it did not work as expected. Vue Select <v-select placeholde ...

Encompassing object with Mobx observables

I am searching for the best approach to implement @observable on a deeply nested JSON object structure, such as a tree. The data tree can go quite deep, with each node having multiple properties. However, I only need to observe one specific property in eac ...

A guide on integrating the vue3-openlayers plugin into a Nuxt project

I am currently working with Vue3 and have the main.ts file set up as follows: import { createApp } from "vue" import App from "./App.vue"; //In the context of nuxt3, how can I include OpenLayersMap? import OpenLayersMap from "vue3 ...

Utilize the power of Request.JSON to send an HTML array as a post

I have a piece of HTML code that includes form elements: First name: <input type='text' name='first_name' value='' /><br/> Last name: <input type='text' name='last_name' value='' / ...

In Next.js, the 404 error page is displayed using getInitialProps

Currently, I am learning how to redirect users in getInitialProps by following a helpful example. Here is the link to the example I am referring to However, I encountered an issue where when I try to return a 404 error using the code snippet provided, in ...