2017-09-13 43 views
0

我有這樣的for循環中檢索,我檢索用戶的進度For循環只顯示從火力

打字稿最後一個數據:

his.userProgress = af.object('/UserProgress/' + this.currentUser + '/', { preserveSnapshot: true }); 

    this.userProgress.subscribe(snapshots => { 
     snapshots.forEach(snapshot => { 
      this.userScores.push(snapshot.val()); 
     }); 
     console.log(this.userScores); 

     //set this one to i<=8 because total no. of quizzes are 9. which means this.userScores.length -1 
     for(var i=0; i <= 8; i++){ 
      if (this.userScores.length == i) { 
       this.scores = [{ 
        None: "Nothing Recorded" 
       }]; 
       console.log("Nothing"); 
      } 

      else if (this.userScores.length >= i) { 
       this.scores = [{ 
        Chapter:this.userScores[i].Chapter_Quiz, 
        QuizNo:this.userScores[i].Quiz, 
        Score:this.userScores[i].Score, 
       }]; 
       console.log("With Scores"); 
      } 
     } 

    }); 

首先,它會檢查是否存在userScores []長度不0或大於或等於0.如果該測驗沒有分數,則將顯示「無記錄」,否則將顯示分數。

HTML:

<ion-card> 

<ion-list *ngFor="let score of scores"> 
    <ion-card-header> 
    {{score.Chapter}} 
    </ion-card-header> 

    <button ion-item *ngIf="scores.length < 0"> 
    <ion-icon name="planet" item-start></ion-icon> 
    {{score.None}} 
    </button> 

    <button ion-item *ngIf="scores.length >= 0"> 
    <ion-icon name="planet" item-start></ion-icon> 
    {{score.Score}} 
    </button> 

</ion-list> 

我有問題

在那裏只顯示最後一個記錄。我做錯了什麼?

Displays MitAdapt only on my View

預期輸出:

If finished with the 1st quiz: 

1st: Score 
2nd: Nothing Recorded 
3rd: Nothing Recorded 
.... 


if no score at all: 
1st: Nothing Recorded 
2nd: Nothing Recorded 
..... 
+0

哪一個日誌顯示? – Vega

+0

@Vega它只顯示MitAdapt。我從我的console.log中添加了輸出 – AngularNewbie

回答

1

首先,在循環的每次迭代,你在this.scores變量改變值的時候,其實你應該推動它來將數據從先前的測驗存儲。

改爲使用this.scores.push

您也可以更改for循環中的條件並使用i < this.userScores.length使其取決於數組的長度。

然後改變ngIf在html檢查score.Score存在與否。如果沒有,那麼沒有分數

0

那麼從你的代碼好像this.userScores.length = 9總是比循環中的索引ii只有從變化到08)更大。因此,對於每個循環迭代,最後一個塊(else if塊)被執行。由於您不是動態更改/添加到this.scores數組,而是僅分配給對象本身(不會更改this.scores的數組索引或推送到現有的this.scores列表),因此當前迭代this. userScores[i]的索引中的值將被存儲到每個迭代的this.scores。在最後一次迭代時,無論this.userScores[8]的值是this.scores,該列表只有length = 1

有意義嗎?