![](/img/trans.png)
[英]Angular Material - mat-table not rendering data from rest api
[英]Angular Material - Mat-table not displaying data from REST API
我一直在嘗試實現一個帶有分頁和排序的墊子表,但沒有成功。
我完全迷失了 datasource.ts 文件。
當我記錄 this.dataSource.data 時會顯示數據,但是當我在 ngOnInit 中的 this.getUsers() 之后記錄 this.dataSource.data 時,它返回 undefined
帳戶列表.component.ts
@Component({
selector: 'app-account-list',
templateUrl: './account-list.component.html',
styleUrls: ['./account-list.component.css']
})
export class AccountListComponent implements OnInit {
@ViewChild(MatPaginator, {static: false}) paginator: MatPaginator;
@ViewChild(MatSort, {static: false}) sort: MatSort;
@ViewChild(MatTable, {static: false}) table: MatTable<AccountListItem>;
dataSource: AccountListDataSource;
data: User[];
/** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
displayedColumns = ['id', 'name'];
constructor(private accountManagementService: AccountManagementService) {
}
ngOnInit() {
this.dataSource = new AccountListDataSource();
this.getUsers();
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
}
getUsers() {
this.accountManagementService.getAllAccounts().subscribe((response:any) => {
this.dataSource.data = response.content;
});
}
}
賬戶管理服務.ts
getAllAccounts(): Observable<any> {
return Observable.create(observer => {
this.apiService.get({
endPoint: `/${this.PREFIX}/`
}).subscribe((responseData) => {
observer.next(responseData);
});
});
}
帳戶列表-datasource.ts
export class AccountListDataSource extends DataSource<User> {
data: User[] = [];
paginator: MatPaginator;
sort: MatSort;
constructor() {
super();
}
/**
* Connect this data source to the table. The table will only update when
* the returned stream emits new items.
* @returns A stream of the items to be rendered.
*/
connect(): Observable<User[]> {
// Combine everything that affects the rendered data into one update
// stream for the data-table to consume.
const dataMutations = [
observableOf(this.data),
this.paginator.page,
this.sort.sortChange
];
this.paginator.length = this.data.length;
return merge(...dataMutations).pipe(map(() => {
return this.getPagedData(this.getSortedData([...this.data]));
}));
}
結果
解決了! 我忘記在 html 模板中為 mat-table 設置數據源
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.