For循环仅显示从firebase检索的最后数据

时间:2017-09-13 18:49:06

标签: arrays angular typescript firebase ionic-framework

我有这个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.如果该测验没有得分,它将显示“Nothing Recorded”,否则它将显示得分。

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
.....

2 个答案:

答案 0 :(得分:1)

首先,在循环的每次迭代中,您正在更改this.scores变量中的值,而实际上您应该将其推送以存储先前测验中的数据。

改为使用this.scores.push

您还可以更改for循环中的条件,并使用i < this.userScores.length使其依赖于数组的长度。

然后更改html中的ngIf以检查score.Score是否存在。如果没有,则没有得分

答案 1 :(得分: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

有道理吗?

相关问题