Using an HttpInterceptor in Angular 1.5 for managing timeouts

Hello everyone,

I have been attempting to implement a global httpInterceptor that will display a custom popup message when a client timeout occurs, rather than a server timeout. I came across a helpful article on this topic: Angular $http : setting a promise on the 'timeout' config. I tried converting the solution provided in the article into an httpInterceptor, but unfortunately, it is not functioning as expected and is exhibiting some strange behavior.

 $provide.factory('timeoutHttpInterceptor', function ($q, $translate, $injector) {

        var timeout = $q.defer();

        var timedOut = false;

        setTimeout(function () {
            timedOut = true;
            timeout.resolve();
        }, 10000);
        return {
            request: function (config) {
                config.timeout = timeout.promise;
                return config;
            },
            response: function(response) {
                return response;
            },
            responseError: function (config) {
                if(timedOut) {
                    var toastr = $injector.get('toastr');
                    toastr.custom('network', $translate('title'), $translate('label'), { timeOut: 5000000000000, closeButton: true, closeHtml: '<button></button>' });
                    return $q.reject({
                        error: 'timeout',
                        message: 'Request took longer than 1 second(s).'
                    });
                }
            },
        };
    });

Answer №1

To incorporate a timeout functionality in your code, utilize the $timeout service to obtain a promise and then assign it to config.timeout. Check out the code snippet provided below for reference.

.factory('timeoutHandler', ['$q','$timeout', function($q,$timeout) {
    return {
      request: function(config) {
        // Set a promise with a timeout and flag it as timed out. No need to trigger $digest, so pass false as the third parameter
        config.timeout = $timeout(function(){ config.timedOut = true },2000,false);
        return config;
      },
      responseError: function(rejection) {
        if(rejection.config.timedOut){ // Show a popup if the request was rejected due to timeout
            alert('The request exceeded the time limit of 1 second.');
        }
        return $q.reject(rejection);
      }
    };

For a complete and functional example, refer to this link: http://jsfiddle.net/2g1y4bk9/

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

Error when sending Angular 4 GET request with multiple Headers results in a 400 bad request code

I've been attempting to perform a POST request with headers in order to receive a response. The Angular code snippet I'm currently using for this request is shown below: const headers = new HttpHeaders({ 'Content-Type': 't ...

Is there a way to modify the package version with yarn, either upgrading or downgrading?

Is there a way to downgrade the version of a package using yarn's "dependencies" feature? ...

A guide to accessing the currently hovered element on a Line Chart with Recharts

Just diving into this community and also new to ReactJS :( https://i.stack.imgur.com/k682Z.png I'm looking to create a tooltip that displays data only when hovering over the value 1 line. Unfortunately, the current tooltip is not behaving as expecte ...

When I open my website in a new tab using iOS and Chrome, the appearance of the absolute element is being altered

I am experiencing an issue with a div that is positioned absolutely at the bottom left of my website. When I open the site in a new tab using <a target="_blank" href="./index.html">, the bottom value is not being applied correctly ...

jQuery - Error: Unexpected token SyntaxError

I'm new to jQuery and facing a challenge with an AJAX request. I have a server on my local network running a Python service. When I make a request to the server through the browser using the URL: http://192.168.0.109:5000/api/environment?seconds=10 ...

Is there a way for me to compare a string A1 with a value A2 located in index 0 within an array of values?

In my current task, I am attempting to compare two sets of strings: A1 must match A2 when selected. However, if A1 is chosen along with B1, C1, or D1, the comparison should return false. Similarly, selecting B1 should result in a match with only B2, while ...

Vanilla JavaScript: toggling text visibility with pure JS

Recently, I started learning javascript and I am attempting to use vanilla javascript to show and hide text on click. However, I can't seem to figure out what is going wrong. Here is the code snippet I have: Below is the HTML code snippet: <p cla ...

Numerous functionalities within the Angular configuration

Currently facing a hurdle in my first Angular project. The issue lies in implementing two functions in the Angular config. First function is for Facebook connect using ngFacebook Second function is for routing with ui-router The challenge arises when b ...

The function `open` is not a valid prop for the `Dialog` component

Upon clicking an icon, a dialog box containing a form should appear for either adding a tab or deleting a specific tab. I have utilized reactjs, redux, and material-ui for the components. While I am able to display the dialog box when the icon is clicked, ...

Issue with filtering of values returned by functions

I've been working with Angular's currency filter and I've run into an issue. It doesn't seem to be filtering the data that is returned from a function. I have a feeling that I might be missing something, perhaps it has to do with how th ...

AngularJS and jQuery offer a convenient way to restrict the selection of future dates in a datepicker

Hello, I am having trouble disabling future dates on my datepicker. I have tried multiple methods but haven't been successful. Can you please point out where I might be going wrong? <div class="input-group date"> <input type="text" clas ...

What is the best way to incorporate auto refresh in a client-side application using vue.js?

Disclaimer: I have separated my client application (Vue.js) from the server side (DjangoRest). I am utilizing JWT for validating each request sent from the client to the server. Here is how it works - The client forwards user credentials to the server, an ...

Leveraging a nodejs script integrated with socket.io within an angular/electron hybrid application

I have successfully created an electron/angular app that is functioning well. Additionally, I have developed a nodejs script to open a socket.io server using typescript + webpack to generate all files in a bundled js file. My challenge arises when trying ...

A compilation of category listings derived from two arrays of objects that share a common parent ID

I have a challenge with two arrays of objects connected by a parent ID. My goal is to create a categorized list where each category contains the corresponding data set. The structure should consist of a header (category) followed by buttons (data) related ...

What is the solution for untangling this complicated Javascript variable referencing issue?

Currently facing an issue that needs to be addressed: app.controller 'MainCtrl', ($scope, TestData) -> $scope.name = 'World' TestData.get(0).then (data)-> $scope.elem = data TestData.get(1).then (data)-> $scope ...

Having trouble modifying a nested object array within a treeview component in Reactjs

Thanks for your help in advance! Question: I'm having trouble updating a nested object of an array in a treeview using Reactjs. Please refer to the code and sandbox link below: https://codesandbox.io/s/cocky-leakey-ptjt50?file=/src/Family.js Data O ...

Error: The application encountered an issue while trying to initialize the module

Forgive me for asking, but I have searched many topics with the same name and they didn't help. It seems like everyone has their own specific code. var app = angular.module('iop', []); // Setting up the service factory to create our ...

Adjusting the size of tables in raw JavaScript without altering their positioning

I am attempting to adjust the size of a th element without impacting the position of the next th in the row. Specifically, I want the width of the th to influence the width of the next th accordingly, rather than pushing it to the left. Below is the code ...

Leveraging useContext to alter the state of a React component

import { createContext, useState } from "react"; import React from "react"; import axios from "axios"; import { useContext } from "react"; import { useState } from "react"; import PermIdentityOutlinedIcon f ...

What is the best way to attach an event listener to every child node within a div that is stored in an array of divs?

Currently, I am dedicated to learning JS on my own and have decided to hold off on using jQuery until my JavaScript skills have improved. The objective is to attach an event listener for the click event to all divs of a specific class and have all child n ...