我想为任何寻求此解决方案的人添加我的方法。
我试图让这个在集合中重复使用。它支持检索数据并按指定字段上下排序。不要忘记在 firebase 规则中将排序字段添加到 .indexOn。
我没有设法让分页工作,因为计算 startKey 太难了!
firebase-datasource.ts
首先定义一个模板数据源,我可以将它重用于所有需要它的集合。
import { Component } from '@angular/core';
import { DataSource } from '@angular/cdk/collections';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { AngularFireDatabase } from 'angularfire2/database';
/**
* Sortable Interface - Used for specifying the sort order.
*/
export interface Sort {
field: string;
direction: '' | 'asc' | 'desc';
}
/**
* FirebaseDataSource is a templated datasource for Firebase. At this stage it
* allows:
* * Tracking data updates to the underlying datarecords.
* * Sorting ascending and descending
*
* We have not implemented paging controls as its too difficult with NoSQL. It also
* does not support multi-field sorting.
*/
export class FirebaseDataSource<T> extends DataSource<T> {
/**
* The datachange subscriber emits new data when the Firebase records are updated.
*/
dataChange: BehaviorSubject<T[]> = new BehaviorSubject<T[]>([]);
/**
* The sort change is updated when the sort order is changed.
*/
sortChange: BehaviorSubject<Sort> = new BehaviorSubject<Sort>({field: '', direction: ''});
/**
* Path tracks the path of the list of records. e.g. /items
*/
path: string;
/**
* Keep for cleaning up the subscription
*/
private _sub: Subscription;
/**
* Getters and setters for setting sort order.
*/
get sort(): Sort {
return this.sortChange.value;
}
set sort(sort: Sort) {
this.sortChange.next(sort);
}
/**
* Construct an instance of the datasource.
*
* @param path The Firebase Path e.g. /items
* @param db Injectable AngularFireDatabase
* @param sort Optional initial sort order for the list.
*/
constructor(
path: string,
protected db: AngularFireDatabase,
sort?: Sort) {
super();
this.path = path;
/**
* Sets up a subscriber to the path and emits data change events.
*/
this._sub = this.db.list(this.path).valueChanges<T>()
.subscribe((data) => {
this.dataChange.next(data);
});
if (sort) {
this.sort = sort;
}
}
/**
* Connect to the data source, retrieve initial data, and observe changes.
* It tracks changes to either the underlying data, or to the sort order and remaps
* the query.
*
* @returns Observable<T[]>
*/
connect(): Observable<T[]> {
const dataChanges = [
this.dataChange,
this.sortChange
];
const _that = this;
return Observable.merge(...dataChanges)
.switchMap(() => {
if (_that.sort.field !== '' && _that.sort.direction !== '') {
return this.db.list(this.path, ref => ref.orderByChild(this.sort.field)).valueChanges<T>()
.map((data: T[]) => {
if (_that.sort.direction === 'desc') {
return data.reverse();
} else {
return data;
}
});
} else {
return this.db.list(this.path).valueChanges<T>();
}
});
}
/**
* Cleans up the open subscription.
*/
disconnect() {
this._sub.unsubscribe();
}
}
然后是一个示例用法:
roles-datasource.ts
在相关模块的“提供者”中声明这一点。 (代码未显示)
import { FirebaseDataSource } from '../../shared/firebase-datasource';
import { Role } from './role';
import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
@Injectable()
export class RoleDataSource extends FirebaseDataSource<Role> {
constructor(
protected db: AngularFireDatabase
) {
super('/roles', db);
}
}
现在让我们看看 UI 组件:
all-roles.component.html
忽略工具栏等的无关代码。要注意的重要部分是mat-table 和matSort 指令。
<!-- Toolbar -->
<div class="plr20 mb10 bb-light">
<div fxLayout="row" fxLayoutAlign="space-between center">
<h1>All Roles</h1>
<div>
<a mat-button [routerLink]="['/roles', 'new']">
<mat-icon class="cursor-pointer">add</mat-icon>New Role</a>
</div>
</div>
</div>
<! -- End Toolbar -->
<div class="plr20" fxLayout="column">
<div *ngIf="contentLoading" fxLayout="row" fxLayoutAlign="center">
<div class="spinner-container">
<mat-spinner diameter="48" strokeWidth="4"></mat-spinner>
</div>
</div>
<mat-card class="mb20">
<mat-card-content>
<mat-table #table [dataSource]="dataSource" matSort>
<!--- Note that these columns can be defined in any order.
The actual rendered columns are set as a property on the row definition" -->
<!-- Identifier Column -->
<ng-container matColumnDef="identifier">
<mat-header-cell *matHeaderCellDef mat-sort-header>Identifier</mat-header-cell>
<mat-cell *matCellDef="let role"> {{role.identifier}} </mat-cell>
</ng-container>
<!-- Title Column -->
<ng-container matColumnDef="title">
<mat-header-cell *matHeaderCellDef mat-sort-header> Title </mat-header-cell>
<mat-cell *matCellDef="let role"> {{role.title}} </mat-cell>
</ng-container>
<!-- Last Updated -->
<ng-container matColumnDef="lastUpdated">
<mat-header-cell *matHeaderCellDef mat-sort-header> Last Updated </mat-header-cell>
<mat-cell *matCellDef="let role"> {{role.lastUpdated | date}} {{role.lastUpdated | date: 'mediumTime'}} </mat-cell>
</ng-container>
<!-- Actions -->
<ng-container matColumnDef="actions">
<mat-header-cell *matHeaderCellDef> Actions </mat-header-cell>
<mat-cell *matCellDef="let role"> <a mat-button [routerLink]="['/roles/', role.identifier]">View</a> </mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
</mat-card-content>
</mat-card>
</div>
all-roles.component.ts
最后是 UI 层的实现。出于个人喜好,它捕获MatSort 更新并将它们发送到数据源,因为我不喜欢将 MatSort 直接绑定到数据源层。我还在加载数据时添加了一个简单的 Ajax 加载器。
import { Component, OnDestroy, ViewChild, OnInit } from '@angular/core';
import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import { Role } from './role';
import { RoleDataSource } from './role-datasource';
import { MatSort } from '@angular/material';
@Component({
templateUrl: './all-roles.component.html',
styles: [':host {width: 100% }']
})
export class AllRolesComponent implements OnDestroy, OnInit {
roles: Observable<any>;
contentLoading: boolean;
subs: Subscription[] = [];
displayedColumns = ['identifier', 'title', 'lastUpdated', 'actions'];
@ViewChild(MatSort) sort: MatSort;
constructor(private db: AngularFireDatabase, private dataSource: RoleDataSource) {
this.contentLoading = true;
}
ngOnInit() {
const _that = this;
// simply handles hiding the AJAX Loader
this.dataSource.connect().take(1).subscribe(data => {
this.contentLoading = false;
});
this.subs.push(this.sort.sortChange.subscribe(() => {
_that.dataSource.sort = {
field: _that.sort.active,
direction: _that.sort.direction
};
}));
}
ngOnDestroy() {
this.subs.forEach((sub) => {
sub.unsubscribe();
});
}
}