2017-11-04 216 views
1

我遇到將新對象推送到現有陣列的問題。Angular 4 - >將對象推入陣列

我所試圖做的事 - > 我試圖拉推到現有數組的新卡/對象

app.component.ts

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

     }; 


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

      } 
     } 

應用.component.html

<h1>New Game</h1> 
    <button (click)="newDeck()">Start</button> 

    <p>{{ deck.remaining }} cards left!</p> 

    <div> 
     <h2>Your Hand</h2> 
     <button (click)="deal(2)">Deal</button> <button (click)="deal(1)">Hit</button> 
     <img width="150" src="{{cards.cards[0].image}}"> 
     <img width="150" src="{{cards.cards[1].image}}"> 
     <img width="150" src="{{cards.cards[2].image}}"> 
     <img width="150" src="{{cards.cards[3].image}}"> 
    </div> 

    <!-- <div *ngFor="let card of cards"> 

     <img src="{{card.cards.image}}" width="150px" style="padding: 50px; margin: 10px;"> 

    </div> --> 

是的 - 我的*ngFor已損壞,因爲它似乎並不認爲這些卡片存儲在陣列中。

錯誤 - >嘗試比較'[object Object]'錯誤。只有陣列和迭代被允許

不過,我附上了正在發生的事情的截圖。我可以選擇交易按鈕,但是當我點擊Hit時,計數器只會拉出1張卡,但它不會存儲在陣列中。相反,它作爲一個新對象,並顯示爲card.cards[0].image而不是card.cards[2].image,因爲單擊交易按鈕後已經有2個對象在數組中。

有關如何將新卡插入卡陣列的任何想法? Image

它可以幫助瞭解如何調用時的卡接收 - >

   { 
        "remaining": 50, 
        "deck_id": "1omsivg9l9cu", 
        "success": true, 
        "cards": [ 
         { 
          "image": "http://deckofcardsapi.com/static/img/KS.png", 
          "images": { 
           "svg": "http://deckofcardsapi.com/static/img/KS.svg", 
           "png": "http://deckofcardsapi.com/static/img/KS.png" 
          }, 
          "suit": "SPADES", 
          "value": "KING", 
          "code": "KS" 
         }, 
         { 
          "image": "http://deckofcardsapi.com/static/img/AH.png", 
          "images": { 
           "svg": "http://deckofcardsapi.com/static/img/AH.svg", 
           "png": "http://deckofcardsapi.com/static/img/AH.png" 
          }, 
          "suit": "HEARTS", 
          "value": "ACE", 
          "code": "AH" 
         } 
        ] 
       } 
+0

此行顯得有些棘手:' this.cards.push(this.cards);' –

+0

這行應該改變嗎? –

+0

真的不能說,我不知道,你想達到什麼目的。 –

回答

1

您可以直接使用card.cards對象在ngFor

<span *ngFor="let item of data.cards"> 
     <img src="{{item.image}}" width="150px" style="padding: 50px; margin: 10px;"> 

</span> 
+0

Dude omg你真了不起,謝謝!不是,我只需要學習將新卡與其他卡一起存儲在陣列中。非常感謝你 –

+0

@ChrisSimmons upvote too :)因爲它幫助你 – Aravind

+0

我很猶豫要回答,因爲我有另一個大問題 –