Angular Firebase Firebase List Observable 控制索引显示在 html

Angular4 Firebase FirebaseListObservable control index to display on html

我想在我的 application.So 中创建一个排行榜我需要从 Firebase 数据库中读取名称和总分信息并将它们显示在浏览器上。 我的目标是在浏览器上显示类似这样的内容,但当然用数据库用户名和最高得分替换未知。

Leaderboard

  • First:Unknown,Topscore:Unknown
  • Second:Unknown,Topscore:Unknown
  • Third:Unknown,Topscore:Unknown
  • Fourth:Unknown,Topscore:Unknown
  • Fifth:Unknown,Topscore:Unknown
  • 我的 firebase 数据库是:

    "users" : {
        "Test1" : {
          "totalscore" : 50,
          "username" : "test1"
        },
        "Test2" : {
          "totalscore" : 30,
          "username" : "test2"
        },
        "Test3" : {
          "totalscore" : 20,
          "username" : "test1"
        },
        "Test4" : {
          "totalscore" : 10,
          "username" : "test1"
        },
        "Test5" : {
          "totalscore" : 50,
          "username" : "test1"
        },
        "Test6" : {
          "totalscore" : 30,
          "username" : "test2"
        },
        "Test7" : {
          "totalscore" : 20,
          "username" : "test1"
        },
        "Test8" : {
          "totalscore" : 10,
          "username" : "test1"
        }
      }
    

    通过下面的代码,我可以得到我想要的倒排信息。

    topusers: FirebaseListObservable<any>;
      constructor(db: AngularFireDatabase) {
    
    
            this.topusers = db.list('users', {
            query: {
             orderByChild: "totalscore",
             limitToLast: 10,
            }
            });
       } 
    

    最后使用 *ngFor 我可以显示从第五到第一的 5 个最高分数。

    <ul *ngFor="let topuser of topusers | async">
      <li class = "white" > 
          {{ topuser.username | json }}:
          {{ topuser.totalscore | json }}          
      </li>
    </ul>
    

    我的问题是,有什么方法可以控制 *ngFor,而不是从列表的第一个索引开始,从最后一个索引开始,到第一个结束? 或者我是否可以控制要在浏览器上显示的 FirebaseListObservable 的索引?

    您不一定要操纵 ngFor 的顺序,而是操纵传递到 ngFor 的数据。您可以使用 .map 方法反转从 firebase observable 返回的数据的顺序

    topusers: Observable<any>; // use Observable<> instead of FirebaseListObservable<> since .map is an rxjs method that returns the type Observable
    
    constructor(){
        this.topusers = db.list('users', {
            query: {
                orderByChild: "totalscore",
                limitToLast: 10,
            }
        })
        .map(res => res.reverse());
    }
    

    所以现在传递给 ngFor 的数组被颠倒了。