Sunday 19 March 2017

Populating an array with data from an SQL database and using that array within functions (Javascript, Angular, Node, SQL)

I'm trying to create a Cards Against Humanity clone in an attempt to solidify my understanding of the MEAN stack. I'm very new to Angular and asynchronous programming so please bear with me.

So far I've created a shuffled deck of cards via a GET request, but now I'd actually like to use that data.

I'm populating an array like so:

self.blackCardDeck = [ ];

getCards();

function getCards(){
    $http({
    method: 'GET',
    url: '/cards'
    }).then(function(response){
    self.blackCardDeck = response.data;
    });
}

This code is getting all of the card data from my database, and then populates the array (my shuffled deck). Rather than simply using this in my html, I'd like to be able to use this array in other functions.

For example: I'd like to create a function that uses this deck, slices 6 cards, and sets this new array to the cards that a player is holding.

Something like:

function player(playerName) {
  this.playerName = playerName;
  this.currentCards = [];
}

player1 = new player("Player 1");

var playerArray = [player1, player2, player3, player4];

for (var i = 0; i < playerArray.length; i++) {
 self.playerArray[i].currentCards = self.blackCardDeck.slice(0, 7);  
}

Obviously with the way my code is currently, that's not possible.

Could someone give me some suggestions on where to go from here?

I know I could populate a JSON file with the card information, but I really need to practice async and working with databases. Additionally, I'd eventually like to give users the option to create custom decks, which would potentially require a database(?).

Any recommended reading/general recommendations on my code is greatly appreciated!



via Arrielle Kooiman

No comments:

Post a Comment