【发布时间】:2016-01-23 04:46:21
【问题描述】:
目前我在我的控制器中使用 $http.success().error()。但是,Angular 已弃用成功/错误支持,并且根据样式指南,编写服务器 $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.
});
}
};
});
【问题讨论】:
标签: javascript angularjs http promise