Arrays 角度4->;推送阵列

Arrays 角度4->;推送阵列,arrays,angular,Arrays,Angular,当选择“点击”按钮到卡[]阵列时,需要帮助推新卡。我尝试过无数种方法,但似乎无法解决这个简单的问题。援助是非常宝贵的 @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'ap

当选择“点击”按钮到卡[]阵列时,需要帮助推新卡。我尝试过无数种方法,但似乎无法解决这个简单的问题。援助是非常宝贵的

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

  }

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

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

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

  • 当您收到响应时,您将
    response.json
    重新分配给
    this.cards
  • 当您的
    deal
    方法被调用时,它只需订阅,然后如果条件
    this.cards
    true,则将
    this.cards
    数组推入自身
deal(cardCount)
{
this.\u data.deal(cardCount,this.deck.deck\u id).subscribe(response=>{
const cards=response.json()
如果(卡片){
这个。卡片。推(卡片);
}

})
嘿!我也试过了,但是我收到了错误->错误类型错误:_this.cards.push不是一个函数