【问题标题】:Simulate db operation in angularJs?在angularJs中模拟数据库操作?
【发布时间】:2014-02-17 06:00:45
【问题描述】:

我想在 AngularJs 中模拟一个 async db 操作。 (通过setTimeout)。

我有这个工厂功能代码:(jsbin) 它使用内部 array :

 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 sec 模拟 db 操作)?

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    您可以使用 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;
    

    然后从控制器中这样调用它:

    $scope.items = Items.query().then(function(res){
        alert(res);
        // successfully resolved
    }, function(err) {
        // handle errors
    });
    

    【讨论】:

    • 我需要 jQ 吗?
    • 不,它只使用 angular 的 $q 实现。您需要将其作为工厂依赖注入。
    • 这只是迈向 ng-master 的一步……或者只是一个承诺,如果你愿意的话。 :)
    • 一遇到ng-enlightenment就挂在那里
    • 我将依赖项放在一个字符串数组中,因为我听说缩小器会改变参数值。(($q, $timeout))。现在 - 在您尝试将我的样本与括号符号匹配之后 - 它更加清晰。 非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2015-11-18
    • 1970-01-01
    • 2014-01-05
    • 1970-01-01
    • 1970-01-01
    • 2012-09-13
    • 2017-03-03
    • 2019-07-13
    相关资源
    最近更新 更多