我是新写作服务的人。我在我的工厂调用了一个调用一系列操作的方法。
1)从DB获取数据 2)等待$ promise解决,然后比较&过滤结果 3)返回新的过滤列表
我退出时获得的所有内容$ scope.new_list是一个空对象。有人可以帮我解决我做错的事吗?
people.factory('uniqueContacts', ['apiResource', function(apiResource) {
function getDB() {
return apiResource.query({api_resource:'people'})
}
function generateList(newlistdata){
getDB().$promise.then(function(result){
newlist = _.difference(newlistdata, result);
})
return new_list;
});
}
return{
buildList: function(newlistdata){
return generateList(newlistdata);
}
}
}]);
//in my controller
$scope.new_list = uniqueContacts.buildList(newlistdata);
console.log($scope.new_list) // undefined
答案 0 :(得分:1)
您的服务功能应该从成功返回new_list
getDB().$promise.then(function(result){
newlist = _.difference(newlistdata, result);
return new_list;
})
});
<强>控制器强>
uniqueContacts.buildList(newlistdata).then(function(new_list){
$scope.new_list = new_list;
});
答案 1 :(得分:0)
由于您尝试同步输出异步调用,因此不会输出任何内容。而是试试这个。
// Factory
people.factory('uniqueContacts', [
'apiResource',
function(apiResource) {
function getDB() {
return apiResource.query({api_resource:'people'})
}
function generateList(newlistdata){
return getDB().$promise.then(function(result){
// NOTE: You need to return the data you want the promise to
// resolve with.
return _.difference(newlistdata, result);
}, function (err) {
// TODO: Handle error
).catch(function (err) {
// TODO: Handle error that may have happened in the `then`.
// http://odetocode.com/blogs/scott/archive/2014/04/21/better-error-handling-in-angularjs.aspx
};
}
return {
// NOTE: There is no need to wrap `generateList` in an anonymous
// function when both take the same parameters, you can use the
// function definition directly.
buildList: generateList;
};
}
}]);
// Controller
// NOTE: `buildList` returns a promise that is asynchronously
// resolved/rejected. So in order to get the data returned you must
// use the `then` method.
uniqueContacts.buildList(newlistdata).then(function (list) {
$scope.newList = list;
console.log($scope.newList);
});
<强>参考文献:强>
答案 2 :(得分:0)
您应该等待来自您的请求的回复(承诺)
function generateList(newlistdata){
getDB().$promise.then(function(result){
newlist = _.difference(newlistdata, result);
return new_list;
})
});
或者如果你想处理错误:
function generateList(newlistdata){
getDB().$promise.then(function(result){
newlist = _.difference(newlistdata, result);
return new_list;
}, function(error) {
// TODO something when error
})
});