使用AngularFire获取或创建ID

时间:2016-04-17 22:12:06

标签: angularjs firebase angularfire firebase-realtime-database

我想创建一个可以拥有大量游戏的系统:

var gamePath = new Firebase("https://x.firebaseio.com/games/");
var games = $firebaseObject(gamePath);
games.$bindTo($scope, "games").then(function() {
  // ...
  if (typeof $scope.games[gameId] == "undefined"){
    $scope.games[gameId] = setupEverything(userId);
  }
  else {
    // ...
  }
});

我认为随着游戏列表变得越来越长,这个解决方案变得不可扩展。我想将gamePath更改为用户指定“gameId”,但之后我最终会返回null返回值。什么是正确的angularFire模式更优雅地实现这一目标?

**注意:我首先使用对象的原因是我可以通过gameId方便地将玩家路由到同一个游戏。我认为,这种简单的游戏对象映射非常重要。

1 个答案:

答案 0 :(得分:1)

引用对象列表的$firebaseObject()是一种反模式。如果您指的是对象列表,请使用$firebaseArray()

如果您要在该列表中添加新游戏,请在其上使用$firebaseArray.$add()或(如果您想控制游戏ID)只需将游戏直接添加到Firebase位置即可。由于AngularFire构建于Firebase JavaScript SDK之上,因此可以完美地互操作。

var gamesPath = new Firebase("https://x.firebaseio.com/games/");
$scope.games = $firebaseArray(gamesPath);
var myGamePath = gamesPath.child(gameId);
$scope.mygame = $firebaseObject(myGamePath).$loaded(function() {
  if (!$scope.mygame.$value) {
    myGamePath.set({
      uid: userId,
      startedAt: Firebase.ServerValue.TIMESTAMP
    })
  };
});

这样,新游戏将立即添加到$scope.games,并在调用$scope.mygame时设置为set()