简体   繁体   English

使用拦截器的每个请求的HTTP测量时间

[英]HTTP measure time of each request using interceptor

I'm trying to measure time on http requests in my application. 我正在尝试在应用程序中衡量HTTP请求的时间。 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. 在这种情况下,我的start变量将被新值覆盖。

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. 我正在考虑创建一个将为每个请求保留键的数组,当它结束时,我将能够从该数组(字典)中获取开始时间,但是我不知道如何在requestresponse函数中标识相同的请求。

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. 您可以将开始时间存储在传递给request函数的config对象上。 This object is available in the response interceptor as response.config . 该对象在response拦截器中作为response.config可用。 Make sure to pick a unique property name that's not already used by Angular . 确保选择Angular尚未使用的唯一属性名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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