【问题标题】:How to load (n>2)-level nested data from denormalized dataset with Firebase/AngularFire?如何使用 Firebase/AngularFire 从非规范化数据集中加载 (n>2) 级嵌套数据?
【发布时间】:2014-05-07 18:16:05
【问题描述】:

给定一个非规范化的数据结构,例如:

{
  "users" : {
    "-JMMXslDJkPYmgcwXUzP" : {
      "items" : [ "-JMMXYaWlg_ftL2sKsdp", ... ],
      "name" : "user0"
    },
    ...
  },
  "items" : {
    "-JMMXYac7EMZcr4LIL5u" : {
      "properties" : [ "-JMMWdpWig-L8oIqbeI1", ... ],
      "name" : "item0"
    },
    ...
  },
  "properties" : {
    "-JMMWdpe3WEyjnUM12o2" : {"name": "property0"},
    ...
  }
}

我目前正在像这样加载嵌套的孩子:

<ul ng-init="users = $ref('users')">
    <li ng-repeat="user in users">
        <h1>{{ user.name }}</h1>
        <ul>
            <li ng-repeat="item_id in user.items" ng-init="item = $ref('items/'+item_id)">
                <h2>{{ item.name }}</h2>
                <ul>
                    <li ng-repeat="property_id in item.properties" ng-init="property = $ref('properties/'+property_id)">
                        <h3>{{ property.name}}</h3>
                    </li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

这里的 plunker 展示了仅使用 3 级深度嵌套数据时加载变得多么缓慢:http://plnkr.co/edit/yrRx2FYJEc5BM1MaSQDe?p=preview

如何加快这些数据的加载/渲染速度?

  • 请注意,here 发布的解决方案(为每个集合而不是每个集合项创建一个引用)对我不起作用,因为我的任何/所有嵌套集合都太大了。

【问题讨论】:

  • 您需要对输出的所有数据进行持久的双向绑定吗?如果没有,你看过 bindonce 吗? github.com/Pasvaz/bindonce
  • 很遗憾,我这样做了——至少对于大多数系列来说是这样。我会看看我能做些什么来将我能做的事情切换到 bindonce,但我怀疑这还不够。

标签: angularjs firebase angularfire


【解决方案1】:

这里的问题是编译器。每次这些记录发生变化时,所有这些 ng-repeat 操作都会重新运行,并且数据会一次又一次地下载。相反,使用项目缓存。

既然我已经写了an example of a user cache previously,我就借用它并切换变量以匹配您的示例。您需要对其进行调整以处理属于每个用户的多个项目;原谅我的懒惰:

观点:

<li ng-repeat="user in users" ng-init="item = items.$load(user.item_id)">
    {{user.name}}: {{item.name}}
</li>

还有控制器:

// CONTROLLER

app.controller('ctrl', function ($scope, $firebase, itemCache) {
    $scope.users = $firebase(fb.child('users'));
    $scope.items = itemCache(fb.child('items'));
    $scope.$on('$destroy', $scope.items.$dispose);
});

app.factory('itemCache', function ($firebase) {
    return function (ref) {
        var cachedItems = {};
        cachedItems.$load = function (id) {
            if( !cachedItems.hasOwnProperty(id) ) {
                cachedItems[id] = $firebase(ref.child(id));
            }
            return cachedItems[id];
        };
        cachedItems.$dispose = function () {
            angular.forEach(cachedItems, function (item) {
                item.$off();
            });
        };
        return cachedItems;
    }
});

【讨论】:

  • 缓存似乎对应用程序的性能没有任何显着影响。有没有办法防止 Firebase 在下载数据时阻止应用?
  • Firebase 操作是异步的,不是阻塞的。
  • 我了解,但流式传输的数据量似乎在浏览器流式传输时锁定了浏览器,因此显示为“被阻止”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-19
  • 2015-01-04
  • 1970-01-01
  • 2010-10-06
  • 2018-05-23
  • 1970-01-01
相关资源
最近更新 更多