在搜索教程后,我回复到the Official Example,结果证明它非常直观。
我对您的问题有类似的要求,只需加载一次数据并在客户端管理操作。
但是,我结束了在服务器端处理操作。
让我做一个假设,你有一个返回对象列表的端点。
/api/books/
1:使用 http-call 方法创建服务以获取您的图书端点(book.service.ts)
private booksUrl = "/api/books";
_getBooks(bookId: number, filter='', sortOrder='asc', pageNumber=0,
pageSize=3):Observable<Book[]>{
return this.http.get(this.booksUrl, {
params: new HttpParams()
.set('bookId', _bookId.toString())
.set('filter', filter)
.set('sortOrder', sortOrder)
.set('pageNumber', pageNumber.toString())
.set('pageSize', pageSize.toString())
}).pipe(
tap(_ => this.log('fetched books')),
catchError(this.handleError('getBooks', [])),
map(res => {
res["payload"] = res;
return res["payload"];
})
);
}
定义你的 Book 类
export class Book{
bookId: string;
Title: string;
}
然后我使用数据表原理图创建了一个 Material-Table 组件。
我这样编辑了表数据源
import { Book } from '../books';
import { BookService } from '../book.service';
/**
* Data source for the Masterlist view. This class should
* encapsulate all logic for fetching and manipulating the displayed data
* (including sorting, pagination, and filtering).
*/
export class BooksDataSource implements DataSource<Book> {
private booksSubject = new BehaviorSubject<Book[]>([]);
private loadingSubject = new BehaviorSubject<boolean>(false);
public loading$ = this.loadingSubject.asObservable();
constructor(private bookService: BookService) {}
/**
* 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( collectionViewer:CollectionViewer): Observable<Book[]> {
return this.booksSubject.asObservable();
}
/**
* Called when the table is being destroyed. Use this function, to clean up
* any open connections or free any held resources that were set up during connect.
*/
disconnect(collectionViewer: CollectionViewer): void {
this.booksSubject.complete();
this.loadingSubject.complete();
}
loadBooks(bookId: number, filter = '', sortDirection = 'asc', pageIndex = 0, pageSize = 3) {
this.loadingSubject.next(true);
this.bookService._getBook(bookId, filter, sortDirection,pageIndex, pageSize).pipe(
catchError(e => throwError(e)),
finalize(() => this.loadingSubject.next(false))
)
.subscribe(_books => this.booksSubject.next(_books));
}
}
最后,在 Books.Components.ts(你的组件)
export class BooksComponent implements OnInit {
constructor(private bookService: BookService){}
dataSource: BooksDataSource;
/** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
displayedColumns = ['bookId', 'Title'];
ngOnInit() {
this.dataSource = new MasterlistDataSource(this.bookService);
this.dataSource.loadBooks(1);
}
}
您可以从这里将数据源映射到您的表。
the Official Example 继续展示如何实现排序、分页、过滤。
编码愉快 :-)