javascript - 在AngularJs中模拟数据库操作?

标签 javascript angularjs

我想在 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/

相关文章:

javascript - 如何让键盘+屏幕阅读器访问我的 Accordion ?

javascript - JS 脚本仅在嵌入 scala/html 代码中时才有效

javascript - 新的正则表达式。测试

javascript - 在 AngularJS 的另一个 Controller 中更新变量

javascript - 不能在 ng-click 函数中使用 .then()

javascript - 检测输入字段是否生成了自动建议列表?

javascript - 如何将脚本标记应用于特定元素,而不应用于其他元素

javascript - 如何使用 angular.js 禁用输入框

c# - 如何在 visual studio 2012 中获取 AngularJS 的智能感知

javascript - 如何在 Angularjs 中将计数器值显示为 2 位数字?