【问题标题】:Delegating/ Decorating $http.get in angular以角度委派/装饰 $http.get
【发布时间】:2015-08-04 11:01:42
【问题描述】:

以下页面有一个示例,用于在角度委派 $log 的调试功能。

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

同样,我想委托 $http 服务的获取/发布功能。这样我就可以记录我的应用所做的所有请求。

下面是我的代码

 $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

我错过了什么?

【问题讨论】:

    标签: angularjs decorator


    【解决方案1】:

    需要返回原始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)
    };
    

    【讨论】:

    • @eladcon 答案是不完整的怎么做或改变了什么! 如何返回原始get函数的结果(promise)
    【解决方案2】:

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

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


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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-17
      • 2019-07-06
      • 2021-05-25
      • 1970-01-01
      • 1970-01-01
      • 2014-04-24
      相关资源
      最近更新 更多