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

2019-04-01 23:25发布

问题:

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:

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.');
});