【问题标题】:Get-or-create id with AngularFire使用 AngularFire 获取或创建 id
【发布时间】:2016-04-17 22:12:06
【问题描述】:

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

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”,但最终我会得到一个空返回值。更优雅地完成此任务的正确 angularFire 模式是什么?

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

【问题讨论】:

    标签: angularjs firebase angularfire firebase-realtime-database


    【解决方案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,并在调用set() 时设置为$scope.mygame

    【讨论】:

    • 感谢您的帮助!不过,我仍然有点困惑 - 如果我第二次运行它并控制台“$scope.mygame.$value”,我仍然没有定义。如何运行 if/else 以便检索已创建的值?另外,旁注,我认为您的第二行有错字 (gamesPath) 而不是 (gamePath)。
    • 已修复错字。感谢您的发现。 $loaded() 只会触发一次。这是一种经常被过度使用的方法,通常有更好的解决方案(这似乎不是人们想要的)。例如,如果您试图等待某个值出现在某个位置,我最近写了一个Gist that shows how to wait for a value with most Firebase SDKs。如果您希望在 AngularFire 中完成相同的操作,请参阅 firebase.com/docs/web/libraries/angular/guide/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-21
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多