我想在 AngularJs 中模拟异步数据库操作。 (通过setTimeout
)。
我有这个工厂功能代码:( jsbin )
它使用内部数组
:
shoppingModule.factory('Items', function() {
var items = {};
items.query = function() {
// In real apps, we'd pull this data from the server...
return [
{title: 'Paint pots', description: 'Pots full of paint', price: 3.95},
{title: 'Polka dots', description: 'Dots with polka', price: 2.95},
{title: 'Pebbles', description: 'Just little rocks', price: 6.95}
];
};
return items;
});
Controller
依次调用:
function ShoppingController($scope, Items) {
$scope.items = Items.query();
}
但我想通过 setTimeout
操作模拟异步操作返回数据。 (简而言之 - 我想添加非阻塞延迟)
我尝试了什么?
我尝试使用 $timeout
变量但没有成功。也尝试使用 setTimeout 但没有成功(因为我在方法中没有 $scope
对象。)
问题:
如何将 setTimeout(3秒模拟数据库操作)添加到工厂函数中?
最佳答案
您可以使用 promise 来实现这一点。修改您的代码以使用如下内容:
工厂:
var deferred = $q.defer();
$timeout(function () {
var returnObj = [
{title: 'Paint pots', description: 'Pots full of paint', price: 3.95},
{title: 'Polka dots', description: 'Dots with polka', price: 2.95},
{title: 'Pebbles', description: 'Just little rocks', price: 6.95}
];
deferred.resolve(returnObj);
}, 3000);
return deferred.promise;
然后从 Controller 中这样调用它:
$scope.items = Items.query().then(function(res){
alert(res);
// successfully resolved
}, function(err) {
// handle errors
});
关于javascript - 在AngularJs中模拟数据库操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21363223/