目前我在我的控制器中使用$ http.success()。error()。然而,角度已棄用成功/錯誤支持,並根據風格指南編寫服務器$ http調用的最佳位置是服務。
鑑於此,我想知道如果下面的代碼是正確的方式前進。
控制器:
var funcWithPromise = function() {
// This service's function returns a promise, but we'll deal with that shortly
TestService.getWeather()
.then(function(data) {
if (data.forecast==='good') {
prepareFishingTrip();
} else {
prepareSundayRoastDinner();
}
}, function(response) {
// promise rejected, could log the error with:
$scope.errorDiv = response.data;
console.log('error', response);
//Manipulate DOM
});
};
服務:
app.factory('TestService', function ($http, $q) {
return {
getWeather: function() {
// the $http API is based on the deferred/promise APIs exposed by the $q service
// so it returns a promise for us by default
return $http.get('http://weather')
.then(function(response) {
return response.data;
}, function(response) {
// something went wrong
return $q.reject(response); //Not sure is it must be response or reponse.data here. With reponse I can utilize response.status.
});
}
};
});