angulardatatablesangular-datatables

Server Side Ajax configuration for Angular-datatables for GET Request


I'm using Angular version 5. I need to do Server Side for angular-datatables. It works with POST request but I'm unable to do it with GET request.

There's a sample API (https://angular-datatables-demo-server.herokuapp.com/), It gives same response for GET and POST request. Angular-datatables does server-side for POST but not GET.

Here's a code example (https://stackblitz.com/edit/visible-columns-with-serverside-loading-angular-way).


Solution

  • Finally got it working. I needed to send datatables info via request params. Here's what I did.

     this.dtOptions = {
          paging: true,
          lengthChange: false,
          searching: true,
          pageLength: 10,
          columnDefs: [{ targets: 3, orderable: false }],
          pagingType: 'simple_numbers',
          order: [[0, 'desc']],
          serverSide: true,
          processing: true,
          ajax: (dataTablesParameters: any, callback) => {
            const params = this.objectToHttpParams(dataTablesParameters);
            console.log('params', params);
    
            this.http
              .get(
                'http://myapi.com',
                {
                  params: params,
                  headers: new HttpHeaders().set(
                    'token',
                    localStorage.getItem('token')
                  )
                }
              )
              .subscribe(resp => {
    
                this.result = resp['data'];
    
                callback({
                  recordsTotal: resp['length'],
                  recordsFiltered: resp['length'],
                  data: []
                });
              });
          }
        };
    
    // Helper Function
     objectToHttpParams(obj: any) {
        return Object.entries(obj || {}).reduce((params, [key, value]) => {
          return params.set(
            key,
            isObjectLike(value) ? JSON.stringify(value) : String(value)
          );
        }, new HttpParams());
      }
    

    With these options, I'm able to make it work with GET requests and also send HTTP Params and Headers instead of sending in body.