2015-06-27 56 views
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? 

回答

0

我同意你的意見。如果服務在多個控制器中重複使用,並且不只是簡單地發出HTTP請求,我通常只會將這些代碼放入服務中。

請注意,您的服務代碼不利用承諾鏈接,因此使用承諾反模式。所有你需要的

function getAPotatoChip() { 
    return $http.get(url).then(function(response) { 
     return response.data; 
    }).catch(function(response) { 
     return $q.reject(response.data); 
    }); 
} 

,或者,如果你真的不關心承諾是否被拒絕,該數據或在錯誤的情況下,完全應答:

function getAPotatoChip() { 
    return $http.get(url).then(function(response) { 
     return response.data; 
    }); 
} 
+0

謝謝!所以如果我使用一個函數來調用你提供的函數,如果數據是從catch函數返回的,那麼調用函數就不會將它與有效的響應區分開來嗎?我想我曾嘗試過那樣,那就是發生了什麼事。那就是你的意思是「承諾反模式」? – claireablani

+0

是的,它會,因爲catch函數返回一個被拒絕的承諾。第一個片段相當於你的。 –

+0

所以它發生在我身上,也許你會把$ http函數放在服務而不是控制器中的原因是因爲控制器的幾十個實例可能會在頁面上實例化,但是服務只能實例化一次? – claireablani