了解$ http查询获取结果所花费时间的最佳方法是什么?

时间:2015-11-05 06:21:30

标签: angularjs http service

我想记录$ http查询获取结果所花费的时间。一种解决方案是计算拨打电话之前和之后的时间差。那么,还有其他更好的方法来了解获取结果所需的时间吗?

1 个答案:

答案 0 :(得分:7)

你可以使用$ 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.');
});