1

Need assistance pushing new cards when the "Hit" button is selected to the cards[] array. I've tried a myriad of methods but can't seem to nail this simple issue. Assistance is greatly valued!

      @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
      })
      export class AppComponent {
      title = 'app';
      deck: any;
      cards = [];
      hand = 0;
      cardCount: number;

      constructor(private _data: DataService){
        console.log("Data Service ready to query api");
        this.cards = [];
      };


      newDeck(){
            this._data.newDeck().subscribe(res => this.deck = res.json());

      }

      deal(cardCount){

        this._data.deal(cardCount, this.deck.deck_id).subscribe(response => this.cards = response.json());
        if(this.cards) {
          this.cards.push(this.cards);
        }
      }

  }

2 Answers 2

2

Your approach is wrong , because:

  • When you receive response you reassign response.json to this.cards
  • When your deal method gets called it simply subscribes, and then pushes this.cards array into itself if the condition this.cards is true.

deal(cardCount)
    {
            this._data.deal(cardCount, this.deck.deck_id).subscribe(response => { 
                           const cards = response.json() 
                           if(cards) {
                               this.cards.push(cards);
                           }
    });

Sign up to request clarification or add additional context in comments.

Comments

0

You need to put the code inside subscribe, as it is asynchronous

deal(cardCount){
    this._data.deal(cardCount, this.deck.deck_id).subscribe(response => 
        if(response) {
            this.cards.push(response.json());
        }
    );
}

1 Comment

Hey! I tried this as well but I receive error -> ERROR TypeError: _this.cards.push is not a function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.