2012-11-14 20 views
1

我想在調用$ http的get方法之前添加一些頭文件。我嘗試這樣做:做些什麼並繼續執行類執行

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

,但我得到這個錯誤:

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

我想這樣做沒有崩潰原始類。
我該如何做到這一點?

回答

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

+0

在你的榜樣,服務名稱將是'控制器,而不是'$ myHttp'內myHttp'。 – btford

+0

對。固定。謝謝你選擇了。 – matsko

+0

如果你的服務函數返回一個對象,最好使用factory()而不是service()。 service()是用於構造函數的。如果感興趣,請參閱http://stackoverflow.com/questions/13395686/angularjs-service-in-separate-file/13406613#13406613獲取更多信息。 –

2

當您撥打$ http服務時,您可以在config parameter object中定義您的標頭:

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