Server Side Ajax configuration for Angular-datatables for GET Request

Viewed 3680
2 Answers

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.

This worked for me

Example reference

      ajax: (dataTablesParameters: any, callback) => {
        const params = {};
        this.objectToHttpParams(params , dataTablesParameters , '');
        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: []
            });
          });
      },


  objectToHttpParams(params: any, data: any, currentPath: string) {
    Object.keys(data).forEach(key => {
        if (data[key] instanceof Object) {
          if (currentPath !== '' ) {
            this.objectToHttpParams(params, data[key], `${currentPath}[${key}]`);
          } else {
            this.objectToHttpParams(params, data[key], `${currentPath}${key}`);
          }
        } else {
            if (currentPath !== '' ) {
              params[`${currentPath}[${key}]`] = data[key];
            } else {
              params[`${currentPath}${key}`] = data[key];
            }
        }
    });
  }

Verified and adjusting a couple of things, I was able to replicate the behavior of the native datatable parameters when the serverside parameter is present Credit

Related