How do I implement md-paginator and md-sort in an md-table from a service?

Viewed 476

I'm new to this, I managed to implement my md-table with data provided by a service. Now I'm trying to implement the filter, sorting and pagination functionalities yet I think I'm doing something wrong.

This is my component:

import { Component, OnInit, ViewChild }  from '@angular/core';
import { DataSource }         from '@angular/cdk';

import { Observable }         from 'rxjs/Observable';
import { BehaviorSubject }    from 'rxjs/BehaviorSubject';
import { MdPaginator }        from '@angular/material';

import { Competition }        from '../../competition/competition';
import { CompetitionService } from '../../competition/competition.service'

import 'rxjs/add/operator/startWith';
import 'rxjs/add/observable/merge';
import 'rxjs/add/operator/map';

@Component({
    selector: 'comp-table-cmp',
    moduleId: module.id,
    templateUrl: 'competitions-table.component.html',
})

export class CompetitionsTableComponent{

    displayedColumns = ["compName", "compChamp", "compRunnerup"];
    dataSource: CompetitionsDatasource | null;

    constructor(private competitionService: CompetitionService){ }

    @ViewChild(MdPaginator) paginator: MdPaginator;

    ngOnInit() {
      this.dataSource = new CompetitionsDatasource(this.competitionService, this.paginator);
      console.log(this.dataSource)
    }
}

export class CompetitionsDatasource extends DataSource<any> {
  constructor(private competitionService: CompetitionService, private paginator: MdPaginator) {
    super();
  }

  subject: BehaviorSubject<Competition[]> = new BehaviorSubject<Competition[]>([]);
  get data(): Competition[] { return this.subject.value; }

  connect(): Observable<Competition[]> {
      const displayDataChanges = [
        this.competitionService.getCompetitions()
            .then(res => {
                this.subject.next(res);
            }),
        this.paginator.page,
        ];
      return Observable.merge(this.subject).map(() => {
          const data = this.subject.data.slice();

        // Grab the page's slice of data.
        const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
        return data.splice(startIndex, this.paginator.pageSize);
      });
  }

  disconnect() {
      this.subject.complete();
      this.subject.observers = [];
  }
}

This is the service providing the data:

import { Injectable }    from '@angular/core';
import { Headers, Http, RequestOptionsArgs, URLSearchParams  } from '@angular/http';

import 'rxjs/add/operator/toPromise';

import { Competition } from './competition';
import { Match }          from '../match/match';

@Injectable()
export class CompetitionService {

  private headers = new Headers({'Content-Type': 'application/json'});
  private competitionsUrl = 'api/competitions';  // URL to web api

  constructor(private http: Http) { }

  getCompetitions(): Promise<Competition[]> {
    let options: RequestOptionsArgs = {};
    let params = new URLSearchParams();
    params.append('size', '250');
    options.params = params;
    return this.http.get(this.competitionsUrl,options)
               .toPromise()
               .then(response => response.json()._embedded.competitions as Competition[])
               .catch(this.handleError);
  }
}

I have tried many things, always implementing my changes within the connect() function in the component. Although I'm starting to think that I should be modifying the service.

The problem I'm facing is here I think:

const data = this.subject.data.slice();

there is no "data" in the subject and of course no "slice".

Any ideas? Am I on the right path?

1 Answers
Related