簡體   English   中英

Angular 4->推送到數組

[英]Angular 4 -> push to array

當在cards []數組中選擇了“ Hit”按鈕時,在推動新卡方面需要幫助。 我嘗試了無數方法,但似乎無法解決這個簡單的問題。 援助非常寶貴!

      @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);
        }
      }

  }

您的方法是錯誤的,因為:

  • 收到響應后,您將response.json重新分配給this.cards
  • 當您的deal方法被調用時,它簡單地進行預訂,然后在條件this.cardstruethis.cards數組推入自身。

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

您需要將代碼放入訂閱中,因為它是異步的

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM