如何在服务的md表中实现md-paginator和md-sort?

时间:2017-08-05 17:08:17

标签: angular typescript angular-material2

我是新手,我设法使用服务提供的数据实现我的md-table。现在我正在尝试实现过滤器,排序和分页功能,但我认为我做错了。

这是我的组成部分:

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 = [];
  }
}

这是提供数据的服务:

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);
  }
}

我尝试过很多东西,总是在组件的connect()函数中实现我的更改。虽然我开始认为我应该修改服务。

我认为我面临的问题是:

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

主题中没有“数据”,当然也没有“切片”。

有什么想法吗?我在正确的道路上吗?

1 个答案:

答案 0 :(得分:0)

永远不会调用class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(buttonTapped(_:))) self.navigationItem.rightBarButtonItem = addButton } var valuesFirstSection = ["value1", "value2", "value3"] var valuesSecondSection = ["value1Second", "value2Second", "value3Second"] //if you want to have the same dataSource array then use this //var sharedValues = ["value1Shared", "value2Shared", "value3Shared"] // shared dataSource array func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return valuesFirstSection.count }else { return valuesSecondSection.count } // //if you want to have the same dataSource array then //use this //return sharedValues.count; } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) if indexPath.section == 0 { cell.textLabel?.text = valuesFirstSection[indexPath.row] }else { cell.textLabel?.text = valuesSecondSection[indexPath.row] } return cell //if you want to have the same dataSource array then //use this //cell.textLabel?.text = sharedValues[indexPath.row] //return cell } func buttonTapped(_ sender: UIBarButtonItem) { //if you want to have the same dataSource array then //you need to insert the rows for other sections as well // sharedValues.insert("NewValue0", at: 0) // self.tableView.insertRows( // at: [IndexPath(row: 0, section: 0), // IndexPath(row: 0, section: 1) // ], // with: .automatic) valuesFirstSection.insert("NewValue0", at: 0) self.tableView.insertRows( at: [IndexPath(row: 0, section: 0) ], with: .automatic) } }

您应合并competitionService.getCompetitions(),如下所示:

displayDataChanges

这可以解决您的问题。