【问题标题】:Firebase & Angular - Retrieve and display flattening dataFirebase 和 Angular - 检索和显示展平数据
【发布时间】:2016-06-24 01:13:33
【问题描述】:

我使用以下代码在我的 Firebase 中展平数据。但是当我想用 ng-repeat 显示最喜欢的用户帖子列表时,模板会重复第二次并且完全空白。我该如何纠正这个问题?

  "Post": {
    "xKkdfjjfld856i": {
      "name": "My first post",
      "author": "Miguel"
    },
    "xKkdfjj556FGHh": { ... },
    "xK499DF6FlHjih": { ... }
  },
  "users": {

    "John": {
      favorited_posts {
         "xKkdfjjfld856i": true,
         "xKkdfjj556FGHh": true
      }
    },
    "Mia": { ... },
    "Patrick": { ... }
  },

HTML:

<div ng-repeat="post in favoritedPosts track by $index">
    <div class="card post-card">
       <h1>{{post.name}}</h1>
       <p>{{post.author}}</p>
    </div> 
</div>

控制器:

var userRef = new Firebase("https://myApp.firebaseio.com/users")
var userFavoriteRef = userRef.child($scope.user_id).child("favorited_posts")
var favoritedPosts = $firebaseArray(userFavoriteRef)

userFavoriteRef.once("value", function(snapshot) {

  snapshot.forEach(function(childSnapshot) {

    var key = childSnapshot.key();

    var postRef = new Firebase("https://myApp.firebaseio.com/Posts")

    postRef.child(childSnapshot.ref().key()).once('value', function(postSnapshot) {
      console.log("Look",postSnapshot.val());
      $scope.favoritedPosts = postSnapshot.val();
    });

  });
});

【问题讨论】:

    标签: angularjs firebase angularfire


    【解决方案1】:

    尝试使用$firebaseArray$getRecord (documentation) 根据对象键获取对象值。然后,您将拥有所需的一切,而无需循环异步调用。

    控制器

    var userRef = new Firebase("https://myApp.firebaseio.com/users")
    var userFavoriteRef = userRef.child($scope.user_id).child("favorited_posts")
    $scope.favoritedPosts = $firebaseArray(userFavoriteRef)
    var postRef = new Firebase("https://myApp.firebaseio.com/Posts")
    $scope.posts = $firebaseArray(postRef)
    

    HTML

    <div ng-repeat="post in favoritedPosts">
            <div class="card post-card">
                <h1>{{posts.$getRecord(post.$id).name}}</h1>
                <p>{{posts.$getRecord(post.$id).author}}</p>
            </div> 
    </div>
    

    【讨论】:

    • 它的工作就像一个魅力!你是最棒的谢谢!! :D :D
    • @YngDev31 哇!真的很高兴你成功了:)
    • @adolfosrs 如果帖子节点有数千个帖子并且您正在将所有帖子下载到客户端怎么办?那是好事吗?我不这么认为
    • @ZaidMirza 你说得对。为避免这种情况,您宁愿在调用中设置一些查询参数,并且您还应该根据您的需要以最佳执行方式来构建数据库。 :)
    • @adolfosrs 我发现这个解决方案更适用stackoverflow.com/questions/30299972/…
    猜你喜欢
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    相关资源
    最近更新 更多