角4 - >推送到阵列

时间:2017-11-04 05:55:53

标签: arrays angular

卡片[] 阵列选择“点击”按钮时,需要协助推送新卡片。我尝试了无数的方法,但似乎无法解决这个简单的问题。非常重视援助!

      @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 个答案:

答案 0 :(得分:2)

你的做法是错误的,因为:

  • 收到回复后,您将response.json重新分配给this.cards
  • 当您调用deal方法时,只需订阅,然后在条件this.cardsthis.cards的情况下将true数组推入自身。



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




答案 1 :(得分:0)

您需要将代码放在subscribe中,因为它是异步的

var totalHours = (int)total.TotalHours;
var totalMins = total.Minutes;