2017-11-04 78 views
0

當選擇「點擊」按鈕至卡[]陣列時,需要協助推送新卡。我嘗試了無數的方法,但似乎無法指出這個簡單的問題。援助非常重要!Angular 4 - >推入陣列

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

    } 

回答

1

你的做法是錯誤的,因爲:

  • 當您收到響應重新分配response.jsonthis.cards
  • 當您的deal方法被調用時,它只是訂閱,然後推送如果條件this.cardstrue,則將陣列插入自身。

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

0

你需要把裏面的代碼訂閱,因爲它是異步

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

嘿!我也試過這個,但是我收到錯誤 - >錯誤TypeError:_this.cards.push不是函數 –

+0

修改了上述任何代碼嗎? – Dhyey