2017-11-04 80 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