我想记录 $http 查询获取结果所花费的时间。一种解决方案是计算调用前后的时间差。那么,有没有其他更好的方法来了解获取结果所花费的时间?
最佳答案
您可以为 $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 或您可以设置 $log,或者对数据执行您想要的操作。
$http.get('url').then(function(response) {
var time = response.config.responseTimestamp - response.config.requestTimestamp;
console.log('Time taken ' + (time / 1000) + ' seconds.');
});
关于angularjs - 了解 $http 查询获取结果所用时间的最佳方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33537906/