如何拦截AngularJS $http日志以在页面中显示

前端之家收集整理的这篇文章主要介绍了如何拦截AngularJS $http日志以在页面中显示前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想从AngularJS拦截控制台日志消息并在页面上的div中显示它们.我需要这个来调试PhoneGap应用程序中的ajax流量.

这是我想要捕获的错误的一个示例:

我尝试了这个Showing console errors and alerts in a div inside the page但是它没有拦截Angular错误消息.

我也尝试了答案中建议的解决方案gameover.也没有运气.显然$http正在以不同方式处理错误记录.

解决方法

我想你尝试过的答案有正确的想法,但你要覆盖错误方法. Reading here我可以看到angularJs使用$log而不是console.log,所以拦截你可以尝试覆盖那些.

像这样的东西:

$scope.$log = {
        error: function(msg){document.getElementById("logger").innerHTML(msg)},info: function(msg){document.getElementById("logger").innerHTML(msg)},log: function(msg){document.getElementById("logger").innerHTML(msg)},warn: function(msg){document.getElementById("logger").innerHTML(msg)}
    }

确保在导入angular.js后运行它.

编辑

第二个猜测,覆盖angular.js文件上LogProvider内部类的consoleLog方法

function consoleLog(type) {
  var output ="";
  //arguments array,you'll need to change this accordingly if you want to
  //log arrays,objects etc                       
  forEach(arguments,function(arg) {
    output+= arg +" ";
  });  
  document.getElementById("logger").innerHTML(output);             
}

猜你在找的Angularjs相关文章