一尘不染

Firebase数据已标准化。我应如何基于此结构获取集合?

angularjs

我想我已经接近了,我能够打印出属于用户的书的ID,但一直尝试从Firebase图书参考中获取属于用户的书的列表失败。

我在这里大致遵循该教程:http :
//www.thinkster.io/pick/eHPCs7s87O/angularjs-tutorial-learn-to-rapidly-build-
real-time-web-apps-with-
firebase#item-526e9330d90f99661f00046c

并在此处阅读有关数据非规范化的文档:https : //www.firebase.com/blog/2013-04-12-denormalizing-is-
normal.html

如果要在页面中显示用户,然后在所有书中显示该用户,该怎么办?

火基结构

FB
|
--user
| |
| --user1
|   |
|   --name: "test name"
|   --email: "test@test.com"
|   --books
|     |
|     "-JFZG3coHOAblHZ7XSjK": true
|     "-KJKJASDIUOPIWE9WEeJ": true
|     "-YtUTRGJLNL876F3SSwS": true
|
--books
  |
  --"-JFZG3coHOAblHZ7XSjK"
  | |
  | --title: "book title 1"
  | --ownerId: "user1"
  |
  --"-KJKJASDIUOPIWE9WEeJ"
  |  |
  |  --title: "book title 2"
  |  --ownerId: "user1" 
  |    
  --"-YtUTRGJLNL876F3SSwS"
  |  |
  |  --title: "book title 2"
  |  --ownerId: "user1"

视图

<div data-ng-controller="UsersController" data-ng-init="findOneUser()">
  <h2>Profile</h2>
  <img class="image_preview" data-ng-src="{{user.photoUrl}}">
  <p>Name: {{ user.name }}</p>
  <p>Name: {{ user.email }}</p>
  <a data-ng-href="#/users/{{ userId }}/edit">Edit</a>

  <h2>Coffee Blends</h2>

  <div data-ng-repeat="book in user.books">
    <p>---</p>
    <p>{{user.books}}</p>
  </div>
  <!--<div data-ng-controller="BooksController" data-init="">-->

  <!--</div>-->
</div>

控制者

'use strict';

angular.module('ccApp.controllers.users', ['ccApp.services.users'])
    .controller('UsersController', ['$scope', '$routeParams', '$location', 'angularFire', 'Users',
      function($scope, $routeParams, $location, angularFire, Users){

      $scope.user = {};
      $scope.userId = $routeParams.userId;

      $scope.findOneUser = function(userId){
        if (!!$scope.userId){
          angularFire(Users.find($routeParams.userId), $scope, 'user');
        }
      };

      $scope.updatePhotoUrl = function(url, user){
        $scope.fileUrl = url;
        console.log($scope.fileUrl[0].url);
        user.photoUrl = $scope.fileUrl[0].url;
      };

      $scope.findUsers = function(){
        $scope.users = Users.collection();
      };

      $scope.findWholesalers = function(){
        $scope.wholesalers = Users.collection();
      };

    }]);

服务

'use strict';

angular.module('ccApp.services.users', ['ccApp.services.firebaseRefs'])
  .factory('Users', ['angularFireCollection', 'FireRef',
    function(angularFireCollection, FireRef){
      return{
        collection: function(cb){
          return angularFireCollection(FireRef.users(), cb);
        }
      , find: function(userId){
          return FireRef.users().child('/'+userId);
        }
      };
  }]);

阅读 238

收藏
2020-07-04

共1个答案

一尘不染

首先更新为angularFire 0.6。看上去是0.3。* ish。angularFire已更改为$firebase并具有更强大,更简化的界面。

香草火力基地

我将首先以困难的方式进行操作,因为我认为理解此处的基本原理非常有价值。这相当复杂,我只介绍基本要点。也有很多微小的情况需要处理:

angular.module('app', [])
    .controller('UsersController', function($scope, $firebase, $timeout, $routeParams){
      var userId = $routeParams.userId;
      $scope.user = $firebase(new Firebase('URL/user/'+userId));

      // or, for 3-way binding and automatic writes back to Firebase
      var userRef = $firebase(new Firebase('URL/users/'+userId)).$bind($scope. 'user');

      // grab this users' books using Firebase (the hard way)
      $scope.books = {};
      var booksRef = new Firebase('URL/books/');

      // fetch the user's book list dynamically because it may change in real-time
      var indexRef = new Firebase('URL/user/'+userId+'/books');

      // watch the index for add events
      indexRef.on('child_added', function(indexSnap) {
         // fetch the book and put it into our list
         var bookId = indexSnap.name();
         booksRef.child(bookId).on('value', function(bookSnap) {
            // trigger $digest/$apply so Angular syncs the DOM
            $timeout(function() {
               if( snap.val() === null ) {
                  // the book was deleted
                  delete $scope.books[bookId];
               }
               else {
                  $scope.books[bookId] = snap.val();
               }
            });
         });
      });

      // watch the index for remove events
      indexRef.on('child_removed', function(snap) {
         // trigger $digest/$apply so Angular updates the DOM
         $timeout(function(snap) {
            delete $scope.books[snap.name()];
         });
      });
});

然后是HTML(以下其他示例相同):

<div data-ng-repeat="(bookId, book) in books">
   {{bookId}}: {{book.title}}
</div>

这里没有完全涵盖的一些边缘案例:

  • 数据未按优先级排序
  • 从索引中删除记录时,应在数据路径上调用off()
  • 索引顺序的更改不会更改数据记录的顺序
  • 索引的值未存储在任何地方以供参考(如果有关系)

FirebaseIndex

FirebaseIndex是一个简单的实用程序,它接受像书本清单这样的索引,并以更复杂的方式管理我们刚刚在上面创建的代码。

不幸的是,FirebaseIndex不支持value事件,因此由于angularFire的内部加载机制发生了变化,因此不能在0.5.0之后与angularFire一起使用。因此,它不像以前那么短而甜美。

angular.module('app', [])
.controller('UsersController', function($scope, $firebase, $timeout){
   var userId = $routeParams.userId;
   $scope.user = $firebase(new Firebase('URL/user/'+userId));

   var fb = new Firebase(URL);
   var index = new FirebaseIndex( fb.child('user/'+userId+'/books') );
   $scope.books = {};

   // almost magic
   index.on('child_added', function(snap) {
      $timeout(function() { $scope.books[snap.name()] = snap.val(); });
   });

   index.on('child_removed', function(snap) {
      $timeout(function() { delete $scope.books[snap.name()]; });
   });
});

Firebase.util.join

Firebase-util是功能更强大,更复杂的库,用于规范化路径。由于它返回的对象的工作方式与常规Firebase引用相同,因此也可以与angularFire
0.5及更高版本无缝使用。

angular.module('app', [])
.controller('UsersController', function($scope, $firebase){
   var userId = $routeParams.userId;
   $scope.user = $firebase(new Firebase('URL/user/'+userId));

   var fb = new Firebase(URL);
   var ref = new Firebase.util.intersection( fb.child('user/'+userId+'/books'), fb.child('books') );

   // magic!
   $scope.books = $firebase(ref);
});
2020-07-04