分页 - 如何等待dataSource准备就绪/可用

时间:2017-10-16 08:16:42

标签: json angular typescript pagination

我有一个分页服务和组件工作正常,但第一次加载页面时dataSource为空。第二次,dataSource准备就绪,我可以显示dataTable和paginate。

是否有任何解决方法可以解决此问题,以便在数据准备好/加载后调用该函数?

根据我的尝试,

setTimeOut()不是一个选项。

list-user.service.ts

let registeredUser:USers[] = [];
@Injectable()
export class ListUserService {
    constructor(public loginService:LoginService){}
    getUserDatasource(page:number, limit:number, sortBy?:string, sortType?:DatatableSortType): IPaginableUsers {

      this.loginService.getUsersList().subscribe(
        (res) => {
          registeredUser = res.message
            return registeredUser; 
        }, (err) => {})
    }
    ...
    ...
}

列表users.component.ts

export class ListUsersComponent implements AfterViewInit, OnDestroy {

    ...
    ...
    constructor( private listUserService:ListUserService, private changeDetectorRef:ChangeDetectorRef) {
            this.fetchUserDataSource();
    }
       ngOnInit(){}

    ngAfterViewInit() {
        if (this.datatable) {
            Observable.from(this.datatable.selectionChange).takeUntil(this.unmount$).subscribe((e:IDatatableSelectionEvent) =>
                this.currentSelection$.next(e.selectedValues)
            );

            Observable.from(this.datatable.sortChange).takeUntil(this.unmount$).subscribe((e:IDatatableSortEvent) =>
                this.fetchUserDataSource(this.currentPagination.currentPage, this.currentPagination.itemsPerPage, e.sortBy, e.sortType)
            );

            Observable.from(this.pagination.paginationChange).takeUntil(this.unmount$).subscribe((e:IDatatablePaginationEvent) =>
                this.fetchUserDataSource(e.page, e.itemsPerPage)
            );
        }
    }

    ngOnDestroy() {
        this.unmount$.next();
        this.unmount$.complete();
    }

    shuffleData() {
        this.users$.next(shuffle(this.users$.getValue()));
        this.currentSelection$.next([]);
        this.changeDetectorRef.detectChanges();
    }
       private fetchUserDataSource(page:number = this.currentPagination.currentPage, limit:number = this.currentPagination.itemsPerPage, sortBy:string | undefined = this.currentSortBy, sortType:DatatableSortType = this.currentSortType) {
        if (sortBy) {
          this.currentSortBy = sortBy;
          this.currentSortType = sortType;
        }

        const { users, pagination } = this.listUserService.getUserDatasource( page, limit, sortBy, sortType);

        this.users$.next(users);
        this.currentSelection$.next([]);
        this.currentPagination = pagination;
    }
}

1 个答案:

答案 0 :(得分:0)

你必须在你的list-user-component

中订阅ngOnInit到this.listUserService.getUserDataSource
export class ListUsersComponent implements OnInit,...
{
   page:number=1;
   limit:number=5;
   sortBy:string='';
   ....
   ngOnInit() {
     this.listUserService.getUserDataSource(page, limit, sortBy, sortType).subscribe((res)=>{
         ....here ...
     }
  }