知道$ http查询获取结果所用时间的最佳方法是什么?

问题描述:

我想记录$ http查询获取结果的时间。一种解决方案是计算通话前后的时间差。那么,有没有其他更好的方法来知道获取结果所花费的时间?

+0

如果你不想记录它只是想看到它。使用Chrome开发者工具网络标签。如果你想记录它,那么最好的方法就是我相信时间差计算。 –

+0

好的。我想记录它。 – SaiGiridhar

+0

如果一个或多个答案是正确的,你应该接受(并且如果合适的话),让本网站的其他用户知道哪一个最好,并且正确地回答了你的问题。 – Tristan

您可以使用拦截器$ httpProvider

app.factory('logTimeTaken', [function() { 
    var logTimeTaken = { 
     request: function(config) { 
      config.requestTimestamp = new Date().getTime(); 
      return config; 
     }, 
     response: function(response) { 
      response.config.responseTimestamp = new Date().getTime(); 
      return response; 
     } 
    }; 
    return logTimeTaken; 
}]); 
app.config(['$httpProvider', function($httpProvider) { 
    $httpProvider.interceptors.push('logTimeTaken'); 
}]); 

然后你就可以CONSOLE.LOG或者你也可以设置$日志,或者你想用什么样的数据。

$http.get('url').then(function(response) { 
    var time = response.config.responseTimestamp - response.config.requestTimestamp; 
    console.log('Time taken ' + (time/1000) + ' seconds.'); 
});