我正在将$q
注入工厂,以便处理来自服务器的所有相关方法和回调。我有一个方法将数据添加到mongoDB数据库,工作正常我收到肯定的答案,我解决了承诺,但没有返回到控制器
在控制器中:
$scope.addArticle = function(){
console.log('add article route working');
ArticleService.addArticle($scope.article.title, $scope.article.content, $scope.article.url)
.then(function(){
refresh(); // here is where I am expecting it to return
}
.catch(function(){
$scope.error = true;
$scope.errorMessage = "Something went wrong!";
$scope.article = {};
}));
}
$scope.remove = function(id){
ArticleService.deleteArticle(id)
.then(function(){
refresh();
});
}
在工厂
myApp.factory('ArticleService',
['$q', '$timeout', '$http',
function($q, $timeout, $http){
var article = null;
return({
addArticle : addArticle,
getArticles : getArticles,
deleteArticle : deleteArticle
});
function addArticle(title, content, imgUrl){
var date = getDatetime();
var deferred = $q.defer();
var article = {
title : title,
content : content,
imgUrl : imgUrl,
date
}
$http.post('user/edit/addArticle', article)
.then(function(response){
if(response.status === 200){
deferred.resolve();
}
});
return deferred.promise;
}
function getArticles(){
var deferred = $q.defer();
$http.get('user/edit/getArticles')
.then(function(result){
deferred.resolve(result.data);
/* article = result.data;
return article; */
}, function(error){
});
return deferred.promise;
}
function deleteArticle(id){
var deferred = $q.defer();
$http.delete('user/edit/deleteArticle/' + id)
.then(function(response){
if(response.status === 200){
deferred.resolve();
}
})
return deferred.promise;
}
function getDatetime() {
return (new Date);
};
}]);
删除文章正在以与使用添加文章完全相同的方式将承诺返回给控制器,为什么没有相同的行为?提前谢谢..
答案 0 :(得分:1)
$http
默认情况下将响应发送为promise。无需使用defer
实例创建新承诺。只需返回http调用。
function addArticle(title, content, imgUrl){
var date = getDatetime();
var article = {
title : title,
content : content,
imgUrl : imgUrl,
date
}
return $http.post('user/edit/addArticle', article);
}
然后在控制器中捕获数据。
ArticleService.addArticle($scope.article.title, $scope.article.content, $scope.article.url)
.then(function(response){
console.log(response.data)
refresh(); // here is where I am expecting it to return
}
答案 1 :(得分:1)
您的代码很完美但有一些语法问题。
正确的顺序如下:
$http.get(url)
.then(function(response) {
// response body
}).catch(function(e) {
// catch block
}).finally(function() {
//finally block
});
在代码下面进行语法更正:
.then(function () {
refresh(); // here is where I am expecting it to return
})
.catch(function () {
$scope.error = true;
$scope.errorMessage = "Something went wrong!";
$scope.article = {};
});