简体   繁体   中英

Angular - Observable or Subject for DataSource

I have an Angular 7 application with Mat Tables retrieving data from API. I have assigned dynamic pagination values, that is pageSizeOptions value will be getting changed whenever I load grid based on some dropdown value and by default all the records will be getting displayed.

If API returns 23 records, then pageSizeOptions will have 10,20,23,30,40,50 and by default it will display all 23 records. When next time I change dropdown value, API returns 45 records but this time still my grid displays only 23 records eventhough pageSizeOptions has 10,20,30,40,45,50 and selection shows 45 as selected.

I assume this is due to View/Grid loaded before pageSizeOptions value is assigned since API takes some time to return data. I thought of resolving this issue by implementing Observable/subscribe.

I am not sure, how to implement these for pageSizeOptions. Can someone please help me to resolve this.

let gridData = responseStudents.Students.map(item => new ResponseStudents());
this.myDataSource = new MatTableDataSource(gridData);
this.Count = gridData.length;
this.PageSizeOptions = [this.Count, 5, 10, 25, 100, 500];
//To remove duplicate
this.PageSizeOptions = Array.from(this.PageSizeOptions.reduce((m, t) => m.set(t, t), new Map()).values());

I was able to get a StackBlitz that may accomplish the foundation of what you are looking for. There ended up being some issues with actually refreshing the table when it came to pagination updates done via the component file, so I opted to change the dataSource.

You should essentially be able to take the code shown in the changePageArray() method and implemented for your use case. Add logic where needed, and maybe refresh changeDetection if it isn't propagating to the ui.

Hope this is what you were looking for, happy coding!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM