Missing Search and Pagination Features in Angular DataTable When Using Custom Spinner with REST API"

57 Views Asked by At

I'm using a spinner in my Angular data table to indicate that data is loading. Despite having a large dataset, the default features for "Searching," "Pagination," and column sorting do not appear after the data has been loaded into the table. below is my code

export class MyLayoutComponent implements OnInit, OnDestroy, AfterViewInit 
{
title: string | undefined;

path: string | undefined;

data: any[] = [];

xmlData: String[] = [];

dtOptions: DataTables.Settings = {};
dtTrigger: Subject<any> = new Subject();
selectedRowData: string | undefined;
screenHeight: any;
scrollFraction: any;
scrollYValue: any;
errorAlert: boolean = false;
isLoading: boolean = true;

constructor(private restApi: MyApiService) {}

ngOnInit(): void {
this.dtOptions = {
  pagingType: 'full_numbers',
  pageLength: 100,
  lengthMenu: [100, 200, 300],
  searching: true,
  autoWidth: true,
};
this.fetchData();
}

ngAfterViewInit(): void {}

ngOnDestroy(): void {
this.dtTrigger.unsubscribe();
}

fetchData() {
this.restApi.getMyReq()
  .pipe(finalize(() => this.isLoading = false))
  .subscribe(
    (response: any) => {
      this.data = response;
      this.initializeDataTable();
    },
    error => {
      console.error('Error fetching data', error);
    }
  );
  }

  initializeDataTable() {
    this.dtTrigger.next(0);
  }
  }

When I include a setTimeout() in the initializeDataTable() method, the spinner comes for some time and gets disabled, and after a 2-second delay table appears correctly with all the default features. Below is the relevant code snippet.

  initializeDataTable() {
     setTimeout(() => {
        this.dtTrigger.next(0);
       }, 2000); // Delay of 1 second (1000 milliseconds)
  }

Can anyone offer assistance? Adding a delay isn't an ideal solution, so I'm looking for alternative approaches to address this issue.?

1

There are 1 best solutions below

0
Shubham Goswami On
this.dtOptions = {
  deferRender: true,
  pagingType: 'full_numbers',
  pageLength: 100,
  lengthMenu: [100, 200, 300],
  searching: true,
  autoWidth: true,
  initComplete: () => {
    this.spinnerService.hide() ;// this piece of code fixing my problem. 
  }
};