简体   繁体   English

访问推入数组的项目

[英]Accessing items pushed into array

Within my firebase data I have a games object, and a players object. 在我的Firebase数据中,我有一个游戏对象和一个玩家对象。 Nested within the players object are unique keys that match the games unique keys, these are the games that include players. 嵌套在玩家对象中的是与游戏唯一键匹配的唯一键,这些是包含玩家的游戏。 Then nested within the game unique keys (inside the players object) are the keys of the actual players who entered that particular game. 然后,嵌套在游戏中的唯一键(玩家对象内部)是进入该特定游戏的实际玩家的键。 what I'm trying to accomplish is an ng-repeat of only the games that the current user (player.uid) has joined. 我要完成的任务是仅重复当前用户(player.uid)加入的游戏。 So in the code below I'm checking if the players id (inside the players object) matches their firebase UID, and if it does I'm pushing that into empty array, then the loop should iterate over that array and if the keys in the array match the keys in the games object...it returns true; 因此,在下面的代码中,我正在检查玩家ID(在玩家对象内部)是否匹配其Firebase UID,如果确实将其推入空数组中,则循环应在该数组上进行迭代,以及键是否在其中数组与游戏对象中的键匹配...它返回true; switching the class from 'hideGames', which has a display of none, to 'show games' which has a display of block. 将类从无显示的“ hideGames”切换为有块显示的“ show games”。 This works well if I add the keys to the commented out gamesToShow array, but not in the actual gamesToShow array that should be populated from the loop. 如果我将键添加到已注释掉的gamesToShow数组中,而不是在应该从循环中填充的实际gameToShow数组中添加键,则此方法效果很好。 What am I doing wrong here? 我在这里做错了什么? I have tried moving the gamesToshow array but it still logs empty. 我曾尝试移动gamesToshow数组,但它仍然记录为空。 What do I need to do in order for it to be usable in the for loop? 我需要做些什么才能使其在for循环中可用? Thanks in advance, I posted relevant code, if any thing else is needed let me know. 在此先感谢您发布了相关代码,如果还有其他需要告诉我。 Thanks everyone. 感谢大家。

"games":{  
      "-JwYx6ckhITt2GWOmzLy":{  
         "date":"8/27/2015",
         "host":"Anthony DeVenuto",
         "hostEmail":"anthonydevenuto@gmail.com",
         "location":{  
            "address":"1234 Crooked Rd, Chicago Illl",
            "course":"Crooked Stick"
         },
         "name":"Crooked Stick Run",
         "rules":{  
            "amount":"21",
            "format":"Match Play",
            "holes":"9",
            "perBirdie":"DOES NOT APPLY",
            "perSkin":"DOES NOT APPLY",
            "time":"12:00pm"
         }
      },
      "-Jwi64w0weox4vxIbz8J":{  
         "date":"8/23/2015",
         "host":"Anthony DeVenuto",
         "hostEmail":"anthonydevenuto@gmail.com",
         "location":{  
            "address":"1234 fdsadgad",
            "course":"West Hills Gathering"
         },
         "name":"West Side Shuffle",
         "rules":{  
            "amount":"21",
            "format":"Match Play",
            "holes":"18",
            "perBirdie":"DOES NOT APPLY",
            "perSkin":"DOES NOT APPLY",
            "time":"1:00pm"
         }
      },
      "-Jwx-f7HnjIKdkMnM16D":{  
         "date":"8/23/2015",
         "host":"Andy",
         "hostEmail":"andy@andy.com",
         "location":{  
            "address":"1234 First Ave",
            "course":"WestCode Hills"
         },
         "name":"WestCode Hustle",
         "rules":{  
            "amount":"12",
            "format":"Match Play",
            "holes":"18",
            "perBirdie":"DOES NOT APPLY",
            "perSkin":"DOES NOT APPLY",
            "time":"1:00pm"
         }
      }
   },
   "players":{  
      "-JwYx6ckhITt2GWOmzLy":{  
         "-Jx1uw6iY87HoNJfAngF":{  
            "email":"andy@andy.com",
            "id":"simplelogin:19",
            "name":"Andy"
         }
      },
      "-Jwi64w0weox4vxIbz8J":{  
         "-Jx1uxoJ0H8Pycp7V12s":{  
            "email":"andy@andy.com",
            "id":"simplelogin:19",
            "name":"Andy"
         }
      },
      "-Jwx-f7HnjIKdkMnM16D":{  
         "-Jx1nbKxyLcbwFFIGjh4":{  
            "email":"anthonydevenuto@gmail.com",
            "id":"simplelogin:22",
            "name":"Anthony DeVenuto"
         }
      }
   },
   "users":{  }
}

JS JS

var player = auth.$getAuth();

  $scope.displayGames = function(game){
  var gamesToShow = [];
  // var gamesToShow = ['-JwYx6ckhITt2GWOmzLy', '-Jwi64w0weox4vxIbz8J'];

  var playersRef = fire.child('players');
  playersRef.on('value', function(snapshot){
    var gamesObjects = snapshot;
    gamesObjects.forEach(function(snapshot){
      var gameKeys = snapshot.key()
      var playerKeys = snapshot;
      playerKeys.forEach(function(snapshot){
        if (snapshot.val().id == player.uid) {
          gamesToShow.push(gameKeys);
          console.log(gameKeys)
        }
      });
    });
  });
    for (var i=0;i<gamesToShow.length;i++) {
      var uniqueKeys = gamesToShow[i];
      if (game.$id == uniqueKeys) {
        return true;
      }
    };
  }

HTML template: HTML模板:

<h1>Dashboard</h1>
  <ul>
    <li class="hideGames" ng-repeat="game in games" ng-class="{showGames:displayGames(game)}">
      <a href="#" ng-click="gameDetails(game)">Course: {{ game.name }} <br> Date:{{ game.date }}<br></a>
      <a href="#" ng-click="removeDashboardGame(game)">Remove</a>
    </li>
  </ul>

If I parse correctly, you are trying to get a list of the games that the current user is playing in. If so, this code will do the trick: 如果我正确解析,则您正在尝试获取当前用户正在玩的游戏的列表。如果是这样,则此代码可以解决问题:

var uid = 'simplelogin:19';
var gamesToShow = [];
ref.child('players').on('value', function(gamesSnapshot) {
  gamesSnapshot.forEach(function(gameSnapshot) {
    var playerKeys = Object.keys(gameSnapshot.val());
    playerKeys.forEach(function(playerKey) {
      var player = gameSnapshot.val()[playerKey];
      if (player.id === uid) {
        console.log(gameSnapshot.key());
        gamesToShow.push(gameSnapshot.val());
      }
    });
  });
  console.log(gamesToShow);
});

A JSBin that shows this code working: http://jsbin.com/selisa/edit?js,console 一个JSBin,显示此代码的工作方式: http ://jsbin.com/selisa/edit?js, console

But not that your data structure is pretty bad for the goal you're trying to accomplish. 但是,并不是说您的数据结构对于您要实现的目标而言是非常糟糕的。 You're looping through the players to match them by their key and that makes things complex. 您正在遍历播放器以按其键匹配它们,这使事情变得复杂。 Since players have an existing natural key (their uid) and each player can probably join each game only once, you're better off storing the players in a game under their uid: 由于玩家拥有一个现有的自然键(其uid),并且每个玩家可能只能加入每个游戏一次,因此最好将玩家存储在其uid下的游戏中:

{
  "-JwYx6ckhITt2GWOmzLy": {
      "simplelogin:19": true
  },
  "-Jwi64w0weox4vxIbz8J": {
      "simplelogin:19": true
  },
  "-Jwx-f7HnjIKdkMnM16D": {
      "simplelogin:22": true
  }
}

With this data structure, you can simply get the list of games with a Firebase query: 使用此数据结构,您可以使用Firebase查询简单地获取游戏列表:

ref.child('players')
   .orderByChild('simplelogin:19')
   .equalTo(true)
   .once('value', function(snapshot) { 
       console.log(snapshot.val()); 
   });

As is quite often the case, you can prevent many headaches by optimizing your data structure for how you intend to use it. 通常,可以通过优化数据结构来使用它们,从而避免很多麻烦。

Yet another alternative you may want to consider is to store the games for each player/user under their /users node. 您可能要考虑的另一种选择是将每个玩家/用户的游戏存储在其/ users节点下。 That way you wouldn't even need a query, but you could directly access the games with: 这样,您甚至不需要查询,但是您可以使用以下命令直接访问游戏:

ref.child('users').child('simplelogin:19').child('games').once('value', ...

That's going to be the best-performing solution, since it doesn't even require a query to access the games. 那将是性能最好的解决方案,因为它甚至不需要查询即可访问游戏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM