Best way to know the time taken by a $http query t

2019-04-01 23:06发布

I want to log the time taken by a $http query to fetch the results. One solution will be calculating the difference of time before and after making the call. So, is there any other better way to know the time taken to fetch the results?

1条回答
何必那么认真
2楼-- · 2019-04-01 23:45

You can use an interceptor for $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');
}]);

And then you can console.log or you could setup $log, or do what you want with the data.

$http.get('url').then(function(response) {
    var time = response.config.responseTimestamp - response.config.requestTimestamp;
    console.log('Time taken ' + (time / 1000) + ' seconds.');
});
查看更多
登录 后发表回答