如何将md-table(cdk数据表)连接到要用作数据源的服务?

时间:2017-07-29 18:23:53

标签: angular typescript rxjs angular-material2

对不起,但是我对这个人一无所知。

我有一个方法返回一个对象数组,我使用该对象数组来显示一个表。这是我正在使用的功能:

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

我的 ngOnInit()方法在启动时调用该函数并获得一个使用 ngFor 迭代的竞赛数组,我正在创建表而没有任何问题。

我想要的是实现md-table或cdk-table组件。我使用该UI库完成了应用程序的其余部分。

  • 我知道我的进口是正确的。
  • HTML似乎很好,因为我显示的是单个标题
  • 控制台中没有错误,但 competitionsDataSource 似乎是空的。

我在下面添加了我的文件,我知道问题在于实现或者我是如何尝试填充dataSource的。

以下是比赛课程:

export class Competition {
  compName: string;
  compStart: Date;
  compEnd: Date;
  compFull: number;
  compTeamCount: number;
  compChamp: number;
  compRunnerup: number;
  compType: number;
  compCountry: string;
  _links: {
    self: {
      href: string;
    },
    matches: {
      href: string;
    }
  }
}

这是组件

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

import { Observable }         from 'rxjs/Observable';
import { BehaviorSubject }    from 'rxjs/BehaviorSubject';

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{

    //1- Define my columns
    displayedColumns = ['compName'];
    //2- Define the database as a new database
    competitionsDatabase = new CompetitionsDatabase();
    //3- Define the datasource
    competitionsDatasource: CompetitionsDatasource | null;

    ngOnInit() {
      //4 - declare the datasource.
      this.competitionsDatasource = new CompetitionsDatasource(this.competitionsDatabase);
      console.log(this.competitionsDatasource);
    }
}


export class CompetitionsDatabase {
  competitions: Competition[];
  dataChange: BehaviorSubject<Competition[]> = new BehaviorSubject<Competition[]>([]);
  get data(): Competition[] { 
    this.competitions = [];
    this.competitionService.getCompetitions().then(
      results => {
          results.forEach(result => {
              if (result.compType === 1) {
                  this.competitions.push(result);
                  this.dataChange.next(results);
              }
              //Call Method to retrieve team names.
          });
        return results;
        }
    )
  console.log(this.dataChange);
  return this.competitions;
  }

  constructor(
      private competitionService: CompetitionService,
  ) {}
}

export class CompetitionsDatasource extends DataSource<any> {
  constructor(private _exampleDatabase: CompetitionsDatabase) {
    super();
  }

  /** Connect function called by the table to retrieve one stream containing the data to render. */
  connect(): Observable<Competition[]> {
    console.log('ExampleDataSource#connect')
    return this._exampleDatabase.dataChange;
  }
  disconnect() {}
}

以及HTML

<div class="example-container mat-elevation-z8">
  <cdk-table #table [dataSource]="CompetitionsDatasource" class="example-table">
    <!--- Note that these columns can be defined in any order.
          The actual rendered columns are set as a property on the row definition" -->

    <!-- CompName Column -->
    <ng-container cdkColumnDef="compName">
      <cdk-header-cell *cdkHeaderCellDef class="example-header-cell"> CompName </cdk-header-cell>
      <cdk-cell *cdkCellDef="let row" class="example-cell"> {{competition.compName}} </cdk-cell>
    </ng-container>

    <cdk-header-row *cdkHeaderRowDef="displayedColumns" class="example-header-row"></cdk-header-row>
    <cdk-row *cdkRowDef="let row; columns: displayedColumns;" class="example-row"></cdk-row>
  </cdk-table>
</div>

结果只是标题&#34; CompName&#34;

请帮忙!

1 个答案:

答案 0 :(得分:5)

您无法定义let row,然后对{{competition.compName}}进行数据绑定。您需要将声明切换为let competition或使用row进行数据绑定。

或者:

<cdk-cell *cdkCellDef="let row" class="example-cell"> {{row.compName}} </cdk-cell>

或者:

<cdk-cell *cdkCellDef="let competition" class="example-cell"> {{competition.compName}} </cdk-cell>

此外,您可以通过仅扩展connect()课程来进行数据检索和DataSource。这是表格的Plunker example简化版本。