Reputation: 4919
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?
Upvotes: 2
Views: 1100
Reputation: 182048
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.
Upvotes: 3