简体   繁体   中英

HTTP measure time of each request using interceptor

I'm trying to measure time on http requests in my application. Because I thing this should be done globally I'd like to use interceptor.

I've created one that can log start time and end time of every 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 logs three values to console: start time of my request, then again start time and end time (when request ends).
My problem begins when I'm doing multiple requests (second starts before first ends). In that case my start variable is overridden with new value.

Problem is my interceptor is factory so it is a singleton (please correct me if I'm wrong).

Can I modify my code to easily get actual time each request took?
I was thinking about creating array that will hold key for each request and when it ends I'll be able to get start time from that array (dictionary), but I don't know how to identify same request in request and response functions.

Maybe there is easier and simpler solution to what I'm trying to do?

You can store the start time on the config object passed to the request function. This object is available in the response interceptor as response.config . Make sure to pick a unique property name that's not already used by Angular .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM