【发布时间】: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