首页 > 解决方案 > 将 `combineLatest` 与 Angular 材质表一起使用

问题描述

尝试combineLatest与 Angular Material一起使用Table。试图将MatPaginatorand the MatSortand 结合起来是行不通的。

这是我正在关注的示例。我正在查看“通过 HTTP 检索数据的表”示例。

这是我正在尝试做的事情:

@ViewChild(MatPaginator) private _paginator: MatPaginator;
@ViewChild(MatSort) private _sort: MatSort;

public ngOnInit(): void {

    this._sort.sortChange.subscribe(
        () => {
            console.log("this works");
        }
    );

    combineLatest(
        this._sort.sortChange,
        this._paginator.page
    ).pipe(
        startWith({}),
        switchMap(
            () => {
                return this._userService.getAll();
            }
        ),
        tap(
            (users: IUser[]) => {
                this._data = users;
            }
        )
    ).subscribe();
}

上面代码的问题是combineLatestobservable 只在组件加载时触发一次。我希望它在每次触发排序或分页时触发。当我直接订阅sortChange时,每次我更改排序时它都会触发。

当我更改combineLatestmerge. 它将按预期工作。但是每次更改任何一个时,我都需要结合排序器和分页器的最新结果。但它永远不会与combineLatest. 这里发生了什么?

标签: angularrxjsangular-materialangular-material2

解决方案


您正在将结果combineLatest传递给startWith操作员,该操作员只会发出一次。只需省略startWith运算符,而不是将结果设置在运算符中,而是tap使用subscribe函数,如下所示:

@ViewChild(MatPaginator) private _paginator: MatPaginator;
@ViewChild(MatSort) private _sort: MatSort;

public ngOnInit(): void {

    this._sort.sortChange.subscribe(
        () => {
            console.log("this works");
        }
    );

    merge(combineLatest(
        this._sort.sortChange,
        this._paginator.page), of({}))
    .pipe(switchMap(() => this._userService.getAll()))
    .subscribe((users: IUser[]) => this._data = users);
}

推荐阅读