Angular2 Firebase数据分组

时间:2017-01-06 20:20:03

标签: angular typescript firebase firebase-realtime-database angularfire

我希望每个新组都有一个带有标题的重复数据。我的数据模型很简单

{
  "-K_kNx9_F2-eTul8548y": {
    "title": "Registration",
    "startTime": "2017-02-04T08:00-06:00"
  },
  "-K_kQhBAJFTYEEqaXDp_": {
    "room": "Cafeteria",
    "startTime": "2017-02-04T12:00-06:00",
    "title": "Lunch",
    "track": "all"
  },
  ...
}

我希望有一个像

这样的div
<div *ngFor="**magic happens**">
  <h2>{{time.label}}</h2>
  <div *ngFor="let session of schedule | async">
    {{session.title}}
  </div>
</div>

我目前有一个解决方案,但它会为所有时段执行ngFor,然后隐藏时间不相等的会话

[隐藏] =&#34;!(session.startTime ==了time.time)&#34;

但这是笨拙的,远非性能。我似乎也无法找到使用AngularFire重复查询。比如说,如果我有一个开始时间列表,然后能够递归查询Firebase。那可行,但似乎不是一件事?目前我的构造函数也很简单

export class ScheduleComponent {    
    schedule;
    times;
    constructor(public af: AngularFire) {
        this.schedule = af.database.list(PATH + '/schedule', { query: { orderByChild: 'title'} });
        this.times = af.database.list(PATH + "/scheduletimes");
    }

}

1 个答案:

答案 0 :(得分:0)

您可以通过执行以下操作来修改您的实现以执行每次查询:

import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';

export class ScheduleComponent {

    times;
    timesWithSchedules;

    constructor(public af: AngularFire) {

        // A list of times, as per your the code in your question:

        this.times = af.database.list(PATH + '/scheduletimes');

        // Compose an observable that adds the schedule for each time. Each
        // emitted value will be an array of time entries. Enumerate the array
        // and add an observable for the time's schedule:

        this.timesWithSchedules = this.times.do(times => times.forEach(time => {

            time.schedule = af.database

                // Query the schedule entries that correspond the time:

                .list(PATH + '/schedule', {
                    query: {
                        orderByChild: 'startTime'
                        startAt: time.time,
                        endAt: time.time
                    }
                })

                // Sort the emmitted array of sessions by title:

                .map(schedule => schedule.sort(compareTitles));

                function compareTitles(a, b) {
                    if (a.title < b.title) {
                        return -1;
                    }
                    if (a.title > b.title) {
                        return 1;
                    }
                    return 0;
                }
        }));
    }
}

您的模板将如下所示:

<div *ngFor="let time of timesWithSchedules | async">
  <h2>{{time.label}}</h2>
  <div *ngFor="let session of time.schedule | async">
    {{session.title}}
  </div>
</div>