1- import { CollectionViewer , DataSource , MdPaginator } from '@angular/material' ;
1+ import { CollectionViewer , DataSource , MdPaginator , MdSort } from '@angular/material' ;
22import { Observable } from 'rxjs/Observable' ;
33import { PeopleDatabase , UserData } from './people-database' ;
44import { BehaviorSubject } from 'rxjs/BehaviorSubject' ;
5+ import 'rxjs/add/observable/combineLatest' ;
6+ import 'rxjs/add/observable/merge' ;
57import 'rxjs/add/operator/map' ;
68import 'rxjs/add/observable/merge' ;
79import 'rxjs/add/observable/combineLatest' ;
@@ -15,12 +17,15 @@ export class PersonDataSource extends DataSource<any> {
1517 _renderedData : any [ ] = [ ] ;
1618
1719 constructor ( private _peopleDatabase : PeopleDatabase ,
18- private _paginator : MdPaginator ) {
20+ private _paginator : MdPaginator ,
21+ private _sort : MdSort ) {
1922 super ( ) ;
2023
21- // Subscribe to page changes and database changes by clearing the cached data and
24+ // Subscribe to paging, sorting, and database changes by clearing the cached data and
2225 // determining the updated display data.
23- Observable . merge ( this . _paginator . page , this . _peopleDatabase . dataChange ) . subscribe ( ( ) => {
26+ Observable . merge ( this . _paginator . page ,
27+ this . _peopleDatabase . dataChange ,
28+ this . _sort . mdSortChange ) . subscribe ( ( ) => {
2429 this . _renderedData = [ ] ;
2530 this . updateDisplayData ( ) ;
2631 } ) ;
@@ -51,12 +56,35 @@ export class PersonDataSource extends DataSource<any> {
5156 }
5257
5358 updateDisplayData ( ) {
54- const data = this . _peopleDatabase . data . slice ( ) ;
59+ const data = this . getSortedData ( ) ;
5560
5661 // Grab the page's slice of data.
5762 const startIndex = this . _paginator . pageIndex * this . _paginator . pageSize ;
5863 const paginatedData = data . splice ( startIndex , this . _paginator . pageSize ) ;
5964
6065 this . _displayData . next ( paginatedData ) ;
6166 }
67+
68+ /** Returns a sorted copy of the database data. */
69+ getSortedData ( ) : UserData [ ] {
70+ const data = this . _peopleDatabase . data . slice ( ) ;
71+ if ( ! this . _sort . active || this . _sort . direction == '' ) { return data ; }
72+
73+ return data . sort ( ( a , b ) => {
74+ let propertyA : number | string = '' ;
75+ let propertyB : number | string = '' ;
76+
77+ switch ( this . _sort . active ) {
78+ case 'userId' : [ propertyA , propertyB ] = [ a . id , b . id ] ; break ;
79+ case 'userName' : [ propertyA , propertyB ] = [ a . name , b . name ] ; break ;
80+ case 'progress' : [ propertyA , propertyB ] = [ a . progress , b . progress ] ; break ;
81+ case 'color' : [ propertyA , propertyB ] = [ a . color , b . color ] ; break ;
82+ }
83+
84+ let valueA = isNaN ( + propertyA ) ? propertyA : + propertyA ;
85+ let valueB = isNaN ( + propertyB ) ? propertyB : + propertyB ;
86+
87+ return ( valueA < valueB ? - 1 : 1 ) * ( this . _sort . direction == 'asc' ? 1 : - 1 ) ;
88+ } ) ;
89+ }
6290}
0 commit comments