2017-10-16 31 views
0

我有一個分頁服務和組件工作正常,除了第一次加載頁面時dataSource爲空。第二次,dataSource已準備就緒,我可以顯示dataTable和paginate。分頁 - 如何等待,直到dataSource準備好/可用

是否有任何修復方法來解決此問題,以便在數據準備就緒/加載後調用該函數?

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; 
    } 
} 

回答

0

必須在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 ... 
    } 
    } 
+0

不,不會/沒有工作。我沒有更新我的問題,並添加了其餘的代碼,以便更容易理解整個概念。請。檢查我的更新 –

+0

我不確定,但我認爲this.listUserService.getUserDatasource()返回一個observable,所以你必須訂閱這個observable – Eliseo

相關問題