Angular NGRx Pagination

49 Views Asked by At

i am working on a table that paginates list of staff on angular with Ngrx for managing the states but when i paginate i could get it work to fetch the data from the store in stead of sending request to the server for every revisited page.

here is my code

on staff.effect.ts

export const loadStaffs = createEffect(
  (
    actions$ = inject(Actions),
    staffService = inject(StaffService),
    store = inject(Store<IStaff>)
  ) => {
    return actions$.pipe(
      ofType(StaffActions.loadNewStaff),
      withLatestFrom(store.select(selectPagination)),
      exhaustMap(([action, staffs]) => {
     

          return staffService.getAll(action.params).pipe(
            map((staffsList) =>
              StaffActions.loadStaffSuccess({ staffs: staffsList })
            ),
            catchError((error: { message: string }) =>
              of(StaffActions.loadStaffFailure({ errorMsg: error.message }))
            )
          );

        return EMPTY;
      })
    );
  },
  { functional: true }
);

the reducer

 on(StaffActions.loadStaffSuccess, (state, action) => {
    return staffAdapter.setAll(action.staffs.result, {
      ...state,
      pagination: action.staffs.pagination,

    });
  }),

the component

 constructor(
    private store: Store<AppStateModel>,
    private _liveAnnouncer: LiveAnnouncer,
    public dialog: MatDialog,
    private staffService: StaffService,
    private router: Router,
    private activatedRoute: ActivatedRoute
  ) {
    this.dataSource.paginator = this.paginator;
    this.params = this.staffService.getParams();
    console.log(this.params);
    this.store.dispatch(StaffActions.loadNewStaff({params: this.params}));

  }

  ngOnInit(): void {
    this.activatedRoute.queryParams.subscribe(params => {
      this.params = { ...this.params, ...params };
      console.log(this.params);
      this.fetchData(this.params);
    });

  }

  fetchData(params: Params){
    console.log(this.params);
    this.staffService.setParams(this.params);
    console.log(this.params);
    this.store.dispatch(StaffActions.loadNewStaff({params: this.params}));
    this.staffs$ = this.store.select(getStaffList);

    this.store.select(selectPagination).subscribe((data) => {
      this.dataSource.data = Object.values(data.entities);
      this.pagination = data.pagination;
      console.log(data);
      this.sortDataSource(); // Sort the data source after it is updated
    });
    const currentUserString = localStorage.getItem('userData');
    this.currentUser = currentUserString ? JSON.parse(currentUserString) : null;
    console.log(this.currentUser);
    if (this.currentUser) {
      this.sortDataSource(); // Sort the data source if there is a current user
    }
  }  



handlePageEvent(event: PageEvent) {
    this.pageEvent = event;

    // Update the params object with the new page number and page size values
    this.params = {
      ...this.params,
      pageNumber: event.pageIndex + 1,
      pageSize: event.pageSize
    };

    // Dispatch an action to load the new page data with the updated params
    this.store.dispatch(StaffActions.loadNewStaff({ params: this.params }));

    // Update the query parameters in the URL
    this.router.navigate([], {
      relativeTo: this.activatedRoute,
      queryParams: this.params,
      queryParamsHandling: 'merge',
      preserveFragment: true
    });

  }

the HTML

   <mat-paginator [length]="pagination.TotalCount"
               [pageSize]="pagination.PageSize"
               [pageSizeOptions]="[10, 20, 50]"
               [pageIndex]="pagination.CurrentPage -1"
               [showFirstLastButtons]="true"
               (page)="handlePageEvent($event)">
</mat-paginator>
0

There are 0 best solutions below