AngularFire: How to filter a synchronized array?

与世无争的帅哥 提交于 2019-12-23 05:29:28

问题


Consider a set of items and users. Each user can have one or more items. The set of items can be quite big, but every user will normally have small amount of items.

app:
  items:
    item1:
      name: 'table'
      color: 'white'
      createdAt: '2014-08-09T12:54:58.803Z'
    item2:
      name: 'macbook air'
      color: 'silver'
      createdAt: '2014-06-09T12:54:58.803Z'
    item3:
      name: 'firebase t-shirt'
      color: 'yellow'
      createdAt: '2014-07-09T12:54:58.803Z'
  users:
    user1:
      items:
        item1: true
        item3: true
    user2:
      items:
        item2: true

Given a user id, e.g. user1, I would like to display a list of user's items, sorted by createdAt:

yellow firebase t-shirt
white table

Every update on the Firebase server should be reflected in the app view.

I guess the view should look like this:

<div ng-repeat="item in items | orderBy:'createdAt'">
  {{ item.color }} {{ item.name }}
</div>

But, I can't figure out an easy way to set up $scope.items.

This is what I currently do:

var userItemsRef = new Firebase(FIREBASE_ROOT + '/users/user1/items');
$scope.userItems = $firebase(userItemsRef).$asArray();

$scope.userItems.$loaded(function() {
  $scope.userItems.$watch(setItems);
  setItems();
});

function setItems() {
  var promises = $scope.userItems.map(function(userItem) {
    var itemRef = new Firebase(FIREBASE_ROOT + '/items/' + userItem.$id);

    return $firebase(itemRef).$asObject().$loaded();
  });

  $q.all(promises).then(function(items) {
    $scope.items = items;
  });
}

Is this the best way to utilize AngularFire?


回答1:


It would probably be simplest to store the items by user. So a structure like this:

/app/items/$user_id/$item_id/...

This would allow for the items belonging to a particular user to be retrieved like so:

var userId = 'user1';
var ref = new Firebase(FIREBASE_ROOT + '/items/' + userId);
$scope.items = $firebase(ref).$asArray();

If this isn't possible, because items are shared between users, it's probably simplest to use a join lib.

var userId = 'user1';
var userIndexRef = new Firebase(FIREBASE_ROOT + '/users/' + userId + '/items');
var itemsRef = new Firebase(FIREBASE_ROOT + '/items/');
var ref = Firebase.util.intersection(userIndexRef, itemsRef);
$scope.items = $firebase(ref).$asArray();

But generally, it's safest and simplest to take the first route.



来源:https://stackoverflow.com/questions/25224499/angularfire-how-to-filter-a-synchronized-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!