【问题标题】:Do Something And Continue Class Execution做某事并继续执行类
【发布时间】:2012-11-14 15:51:26
【问题描述】:

我想在调用 $http 的 get 方法之前添加一些标题。我试过这个:

$http = $originalHttpMethod;
this.$http = function() {
   //add headers
   return $http
};
$http.get({url:'http://...'});

但我收到此错误:

TypeError: Object function () {return $http} has no method 'get'.

我想在不崩溃原始类的情况下做到这一点。
我该怎么做?

【问题讨论】:

    标签: javascript oop angularjs


    【解决方案1】:

    提供服务而不是在本地做任何事情。这样您就可以更轻松地在您的应用程序中重用它。

    module.factory('$myHttp', ['$http', function($http) {
      //do your stuff
      return $http;
    }]);
    

    然后在您的控制器、指令或任何其他服务中,将其作为依赖项包含并像这样使用它:

    $myHttp.get()
    

    以下是有关此的更多信息:

    http://www.yearofmoo.com/2012/10/more-angularjs-magic-to-supercharge-your-webapp.html#you-should-be-using-custom-services

    【讨论】:

    • 在您的示例中,服务名称将是控制器内的myHttp,而不是$myHttp
    • 对。固定的。感谢您接受。
    • 如果你的服务函数返回一个对象,最好使用factory()而不是service()。 service() 用于构造函数。如果有兴趣,请参阅stackoverflow.com/questions/13395686/… 了解更多信息。
    • 好点。我猜在这种情况下,它意味着返回修改后的 $http 对象。
    【解决方案2】:

    您可以在调用 $http 服务时在 config parameter object 中定义您的标头:

    configObj = {url:'http://...', headers: { add your headers here}, ... };
    $http.get(configObj);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-10
      • 2016-10-16
      • 1970-01-01
      相关资源
      最近更新 更多