委托/装饰角度为$ http.get

时间:2015-08-04 11:01:43

标签: angularjs decorator

以下页面有一个示例,用于委托$ log in angular的调试功能。

http://solutionoptimist.com/2013/10/07/enhance-angularjs-logging-using-decorators/

同样,我想委托$ http服务的get / post功能。这样我就可以记录我的应用程序所做的所有请求。

以下是我的代码

 $provide.decorator('$http', ["$delegate", function($delegate) {
  var debugFn = $delegate.get;
  $delegate.get = function() {
    var args = [].slice.call(arguments);

    // Prepend timestamp
    console.log(args[0]);

    // Call the original with the output prepended with formatted timestamp
    debugFn.apply(null, args)
  };

  return $delegate;
}]);

即使它正在记录url,它也会抛出异常

TypeError: Cannot read property 'finally' of undefined
at handleRequestFn (angular.js:17382)
at compileTemplateUrl (angular.js:8270)
at applyDirectivesToNode (angular.js:7885)
at compileNodes (angular.js:7431)
at compile (angular.js:7338)
at applyDirectivesToNode (angular.js:7808)
at compileNodes (angular.js:7431)
at compileNodes (angular.js:7443)
at compile (angular.js:7338)
at angular.js:1630

我错过了什么?

2 个答案:

答案 0 :(得分:5)

您需要返回原始get函数的结果(promise):

$delegate.get = function() {
    var args = [].slice.call(arguments);

    // Prepend timestamp
    console.log(args[0]);

    // Call the original with the output prepended with formatted timestamp
    return debugFn.apply(null, args)
};

答案 1 :(得分:3)

  

这样我就可以记录我的应用程序所做的所有请求。

您可以使用拦截器(请参阅https://docs.angularjs.org/api/ng/service/$http

一个有用的链接示例 - http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/