Intercepting HTTP requests allows for accurate measurement of the duration of each individual

My goal is to accurately measure the time spent on HTTP requests in my application. I believe this should be done universally, so I want to implement an interceptor.

I have created an interceptor that can record the start and end times of each request:

app.factory('httpTimeInterceptor', [function() {

var start;

return {
  request: function(config) {
    start = new Date();
    console.log("START",start);
    return config;
  },
  response: function(response) {
    console.log("START",start);
    var date = new Date();
    console.log("END",date);
    return response;
  }
};
}])

This setup logs three values to the console: the start time of the request, then again the start time and end time when the request concludes.
However, the issue arises when multiple requests are made simultaneously (the second starts before the first ends). This results in the start variable being overwritten with a new value.

The problem lies in the fact that my interceptor is a factory, making it a singleton (please correct me if I'm mistaken).

Is there a way for me to modify my code to easily retrieve the actual time taken for each request?
I am considering creating an array to store keys for each request, allowing me to access the start time when the request finishes, but I'm unsure how to identify the same request in the request and response functions.

Perhaps there is a simpler solution to achieve what I am aiming for?

Answer №1

When using the request function, remember to store the start time in the config object. This information can be accessed later in the response interceptor as response.config. Be sure to select a unique property name that is not already claimed by Angular.

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

Having difficulty installing Axios on Node, despite attempting various solutions found on StackOverflow without success

I am encountering an issue where Node is unable to locate the axios package that I installed. In an attempt to resolve this, I performed the following actions in NPM, believing it was an npm-related problem: npm uninstall axios npm cache clean --force npm ...

I have implemented a code snippet that verifies if the incoming week aligns with the existing week, triggering an alert accordingly

One of the challenges I faced was checking if a newly created week matched with an existing one, and then displaying an alert. Here's how I approached it: $scope.addWeek = function(type,newWeek,index){ var c = $scope.weekList.length + 1; var ...

What about a lightbox with enhanced jQuery features?

As a newcomer to jQuery, I've never experimented with lightboxes before. However, I was tasked with creating something fun for April Fools' Day at work. Naively, I accepted the challenge thinking it would be simple, but now I find myself struggli ...

Executing secure journey within TypeScript

Just came across an enlightening article on Medium by Gidi Meir Morris titled Utilizing ES6's Proxy for secure Object property access. The concept is intriguing and I decided to implement it in my Typescript project for handling optional nested object ...

Coding with Angular 4 in JavaScript

Currently, I am utilizing Angular 4 within Visual Studio Code and am looking to incorporate a JavaScript function into my code. Within the home.component.html file: <html> <body> <button onclick="myFunction()">Click me</button> ...

AJAX working concurrently across multiple threads

After learning that JavaScript is single-threaded (as discussed in this question: If Javascript is not multithreaded, is there any reason to implement asynchronous Ajax Queuing?), I started to explore how this concept applies to my developed application. H ...

Can you provide guidance on downloading a CSV file from a Java Spring controller via GUI while on the move?

Just graduated from college and diving into Software Development. I'm currently working on my first major project. I'm trying to enable users to download a CSV file by selecting the start and end dates of the project. The downloaded file should ...

Is it possible to subscribe to changes in an input type file using FormControl?

After subscribing to the FormControl.valueChanges() triggered by selecting a file on an input, I noticed that the value emitted does not include the full file path. Is there a way to access this information through subscription, or do we need to retrieve i ...

Obtaining information from a intricate string input

{JSON.stringify(walletData.transactions, null, 2)} My goal is to extract backend data and display it as a table. The response has been converted into an array as shown below. [ { "date": "Nov 07, 2023", "description" ...

What steps can I take to incorporate validations in the code so that it can correctly show errors like 'Password is too short' and 'Height is not a valid number'?

I need to update the checkSubmit() function to display the following messages: Passwords do not match Password is too short (minimum 4 characters) Height is not numeric I have successfully implemented the first check, but I am unsure how to approach the ...

Tips for properly implementing setTimeout in React applications

I am currently dealing with the following code snippet: const Button = () => { const [numbers, setNumbers] = useState({ a: 10, b: 30, c: 100, d: new Date() }); const click = () => { setTimeout(click2, 2000); }; const c ...

Assigning ng-model within a nested ng-repeat to use as parameters in an ajax request

How can I make an ajax call using ng-model values as parameters in my AngularJS project? Is it allowed to set ng-model to json data directly? Also, how should I set the scope for ng-model in the controller? Controller EZlearn.controller("testController", ...

Differences Between Mongoose Schema Reference and Embedded Array

My application includes express and mongoose, featuring two schemas: a Blog schema and a Comment schema. I am trying to push a comment array from a form to a single blog using RESTful routes. When I embed the Comment schema in the Blog schema, everything w ...

Extracting a precise value from an array nested within another array

Within my nested associative arrays, I am trying to figure out how to splice a specific value. In a regular array, this is easily done with: arr.splice(arr.indexOf('specific'), 1); But when it comes to an array structure like this: arr['h ...

When trying to import axios from the 'axios.js' file in the 'lib' directory, a SyntaxError was encountered with the message: Unexpected identifier

My server.ts is causing issues. What am I doing wrong? const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const morgan = require('morgan'); const axios = requ ...

Duplicate key error occurred in the collection resulting in Error Handling: E11000

Encountering an issue with the user model I'm utilizing alongside Mongoose and MongoDB to create profiles in my database. The process works smoothly when posting a single user, but throws an error upon logging out and attempting to add another: { ...

Nuxt's axios is encountering difficulties in managing the server's response

Having just started working with Nuxt.js, I encountered an unusual issue. There is an endpoint in my backend API that allows users to reset their password by sending a token along with a new password. Although the request is being sent correctly and the s ...

Updating pages dynamically using AJAX

There's a glitch I can't seem to shake off. I've successfully implemented AJAX for page loading, but an issue persists. When I navigate to another page after the initial load, the new page contains duplicate tags like <head> and <f ...

Creating a button in ReactJS with text displayed under an icon

Presently, I am working with a component that looks like this: https://i.stack.imgur.com/qGCwj.png This is the code for the component: import React from "react"; import {withStyles} from "material-ui/styles"; import Settings from "material-ui-icons/Setti ...

Having trouble updating the DataTable with extra details retrieved from a new URL

I'm currently utilizing the DataTable plugin. After loading the DataTable, my aim is to reload the table, while keeping the existing content intact, and adding information gathered from a separate json file. However, I'm encountering an issue wh ...