Augusto Furlan
Augusto Furlan

Reputation: 155

Datatable Angular 4

[ANGULAR 4 - ts] I'm using the metronic theme and its datatable comes from a remote location this way:

var DatatableJsonRemoteDemo = function () {
//== Private functions

// basic demo
var demo = function () {

    var datatable = $('.m_datatable').mDatatable({
        // datasource definition
        data: {
            type: 'remote',
            source: 'http://localhost/ci/api/Users',
            pageSize: 10,
            saveState: {
                cookie: true,
                webstorage: true
            }
        },

But my API uses a heaader where I have to pass a KEY, how can I do that to fit this request to a key? And where can I by a console.log to see my return? PS: step via post Thanks

Upvotes: 0

Views: 714

Answers (1)

Marius Razoux
Marius Razoux

Reputation: 27

I'm using Metronic with Angular v5.0.5. In order to create a Datatable from a remote location you need to,

import the Service that gets the key you need

import { KeyService } from '../path.to.services/key.service';

Then call it in the component constructor

constructor (private _keyService:KeyService) {}

In the ngOnInit() hook, create your array of options, (I will focus only on the data part)

let options = {
      data: {
        type: 'remote',
        source: {
            read: {
              url: 'http://your_API_URL.com',
              method: 'POST',
              headers: { 'Key': this._keyService.getKey()},
            }
        },
        pageSize: 10,
        saveState: {
          cookie: true,
          webstorage: true
        }
      }

and create your datatable with

let yourdatatable = (<any>$('#TheIdDataTable')).mDatatable(options);

Notes :

  • If you want to use the GET method you need to have at least the 5.0.4 version of Metronic because before the POST method was hardcoded in the theme. See this

  • To use a console.log just put it anywhere you want in the constructor or ngOnInit hook.

  • If you just want to see the return of you API request just go in the network section of your navigator console, filter the request by XHR and fetch and find the one corresponding to your datatable (something like users?datatable%5Bquery%5D=)

  • in order to display your results you may need to map them with a function, I invite you to read the Metronic Documentation and look for the data.source.read.map part.

Good luck !

Upvotes: 2

Related Questions