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