0
我記得在堆棧溢出時看到很多次將角度$ http調用委託給服務而不是在控制器中執行的建議。當需要服務以某種方式修改響應對象時,我可以看到這樣做的清潔程度,然後再將其傳遞迴控制器。
但是,如果不需要修改響應呢?在這種情況下,在控制器中使用一個函數調用服務返回一個$ http請求似乎是多餘的。有什麼其他的原因,我可以知道要保留$ http呼叫服務,而不是控制器?
例如
// in controller
function potatoChipTime() {
chip = chipService.getAPotatoChip();
}
// in service (inject $q and $http)
var service = {
getAPotatoChip: getAPotatoChip
}
return service;
function getAPotatoChip() {
var deferred = $q.defer();
$http.get(url)
.success(function(response) {
deferred.resolve(response);
)}.error(function(error) {
deferred.reject(error)
});
return deferred.promise;
}
// redundant, no? a lot of fuss to get a potato chip?
謝謝!所以如果我使用一個函數來調用你提供的函數,如果數據是從catch函數返回的,那麼調用函數就不會將它與有效的響應區分開來嗎?我想我曾嘗試過那樣,那就是發生了什麼事。那就是你的意思是「承諾反模式」? – claireablani
是的,它會,因爲catch函數返回一個被拒絕的承諾。第一個片段相當於你的。 –
所以它發生在我身上,也許你會把$ http函數放在服務而不是控制器中的原因是因爲控制器的幾十個實例可能會在頁面上實例化,但是服務只能實例化一次? – claireablani