【问题标题】:Sort header not working with data from angular service排序标头不适用于角度服务中的数据
【发布时间】:2018-10-10 12:32:40
【问题描述】:

我尝试使用Angular Material 实现一个不同的基本表(日期、体重)。

排序已经用“MatSort”实现了,对我来说效果很好(参见官方示例here)。

现在我想从 HTTP 请求 GET 中检索数据,并使用角度服务返回 Observables。它适用于填充数据表,但排序不再起作用,标题上没有箭头......

weight.component.ts

  @ViewChild(MatSort) sort: MatSort;
  dataSource = new MatTableDataSource<Weight>();

  constructor(
    private _weightsService: WeightsService,
  ) {}

ngOnInit() {
    this._weightsService.getWeights().subscribe(data => {
      this.dataSource.data = data;
      this.dataSource.data = this.dataSource.data;
    });
  }

  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
  }

weight.component.html

<mat-table #table [dataSource]="dataSource" matSort>
      <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
      <mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
      <!-- Date Column -->
      <ng-container matColumnDef="date">
        <mat-header-cell *matHeaderCellDef mat-sort-header> Date </mat-header-cell>
        <mat-cell *matCellDef="let row"> {{row.date | amDateFormat:'DD/MM/YYYY'}} </mat-cell>
      </ng-container>
      <!-- Weight Column -->
      <ng-container matColumnDef="weight">
        <mat-header-cell *matHeaderCellDef mat-sort-header> Poids </mat-header-cell>
        <mat-cell *matCellDef="let row"> {{row.weight}} </mat-cell>
      </ng-container>
</mat-table>

weight.service.ts

@Injectable()
export class WeightsService {
  constructor(private _httpClient: HttpClient) {}

  getWeights(): Observable<Weight[]> {
    return this._httpClient.get<Weight[]>(URI).map(results => {
      results.forEach(weight => (weight.date = moment(weight.date)));
      return results;
    });
}

weight.ts

import * as moment from 'moment';

export class Weight {
  constructor(public id: number, public date: moment.Moment, public weight: number) {}
}

我已经尝试在数据订阅中移动排序线,但它也不起作用。

我不明白如何从 HTTP 检索数据并让排序正常工作!我已经看到我可以创建一个新的类来实现 DateSource、connect()、disconnect() 并重新编写排序...(see here)。但我不确定我是否需要它,因为我不想覆盖排序。

提前感谢您的帮助!

【问题讨论】:

  • 请提供您的代码。
  • 查看更新后的帖子

标签: angular sorting html-table observable angular-material2


【解决方案1】:

最后的问题是缺少:

import { MatSortModule } from '@angular/material';

我不在家时在 Stackblitz 上测试了一些代码,回来时检索了一些代码,但是我忘记执行此导入...并且使用 MatSort 而不导入它不会引发错误!

我在 angular/material2 上为此 (#11079) 打开一个问题。

【讨论】:

    猜你喜欢
    • 2018-04-13
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    • 2014-10-25
    • 2020-07-09
    • 1970-01-01
    • 2016-07-27
    • 2013-03-30
    相关资源
    最近更新 更多