1

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

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

但我收到此错误:

TypeError: Object function () {return $http} 没有方法'get'。

我想在没有崩溃原始课程的情况下做到这一点。
我该怎么做?

4

2 回答 2

2

当您调用 $http 服务时,您可以在配置参数对象中定义您的标头:

configObj = {url:'http://...', headers: { add your headers here}, ... };
$http.get(configObj);
于 2012-11-15T23:17:10.260 回答
2

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

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

于 2012-11-14T16:07:27.847 回答