我遇到了将数据绑定到Material表
的问题接口
export interface IToDoList {
ID: number,
Comment: string
}
service.ts
getToDoList(ID: string): Observable<IToDoList[]> {
return this._http.get(environment.BASE_API_URL + 'GetToDoList/' + ID)
.map((response: Response) => <IToDoList[]>response.json())
.do(data => console.log('All' + JSON.stringify(data)))
.catch(this.handleError);
}
component.ts
export class DashboardComponent implements OnInit {
bsaFollowup: IBSAFollowup[] = null;
toDoList: IToDoList[] = null;
dataSource = new DashboardDataSource(this._dashboardService)
displayedColumns = ['Comment'];
constructor(private _dashboardService: DashboardService{
}
ngOnInit(): void {
..some code
}
}
export class DashboardDataSource extends DataSource<any> {
toDoList: IToDoList[];
constructor(private _dashboardService: DashboardService) {
super();
}
public connect(): Observable<IToDoList[]> {
return this._dashboardService.getToDoList('xxxxx');
}
disconnect(){}
}
HTML
<mat-table [dataSource]="dataSource">
<ng-container matColumnDef="Comment">
<mat-header-cell *matHeaderCellDef> Commment </mat-header-cell>
<mat-cell *matCellDef="let row"> {{row.comment}} </mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns" ></mat-header-row>
<mat-row *matRowDef="let row; columns:displayedColumns"></mat-row>
</mat-table>
当我运行代码时,表没有显示列,我收到错误(使用F12)
ERROR错误:尝试diff'[object Object]'时出错。只有阵列和 允许迭代
********************************************** UPDATE **********************************************
我将服务改为
getToDoList(psnlUID:string) {
return this._http.get(environment.BASE_API_URL + 'GetToDoList/' + psnlUID)
.map((response: Response) => response.json())
.do(data => console.log('All' + JSON.stringify(data)))
.catch(this.handleError);
}
组件
toDoList: IToDoList[] = null;
dataSource = new MatTableDataSource();
ngOnInit(): void {
this.GetToDoList(this.userID);
this.dataSource = this.toDoList; // I get error
}
GetToDoList(PNSLUID: string) {
this._dashboardService.getToDoList(PNSLUID)
.subscribe(
data => {
this.toDoList = data.result;
},
error => console.log('GetControls Method: ' + <any>error, 'alert alert-danger'));
}
我收到错误(来自this.dataSource = this.toDoList;)
严重级代码描述项目文件行抑制状态 错误TS2322类型'IToDoList []'不能分配给类型 'MatTableDataSource&LT; {}&GT;'。类型中缺少属性'_data' 'IToDoList []'。
答案 0 :(得分:1)
您需要使用服务中的数据初始化MatTableDataSouce
,将组件代码更改为以下内容:
dataSource = new MatTableDataSource();
ngOnInit(): void {
this.GetToDoList(this.userID);
}
GetToDoList(PNSLUID: string) {
this._dashboardService.getToDoList(PNSLUID)
.subscribe( data => {
// Set the dataSource here
this.dataSource = new MatTableDataSource(data.result);
},
error => console.log('GetControls Method: ' + <any>error, 'alert alert-danger'));
}
答案 1 :(得分:0)
可以添加#table <mat-table #table [dataSource]="dataSource">
如果这不起作用。你能在stackBlitz中重现吗? Reference