Angualr Datatables with an AJAX Source

It took me a bit of hacking to get this working exactly the way I wanted so since there appears to be no documentation on this issue on the main angular-datatables page decided to document a little bit with an example.

A little background by default I usually return all of my API requests as {“some_key”: some_data}, however as I found out while trying to plug my API into dataTables this does not always work. After about 30 minutes of hacking around with my code and testing I was able to successfully plugin a Angular Datatables Frontend with my Flask backend. Below I will provide the actual solution I am using at this moment in time in hope that it will provide insight any issue you have with connecting the two.

The problem

By default datatables looks for an aaData key in the object being passed to it. However $http in angular is passing all of the data to a ‘data’ key so I had to fix that with the withDataProp method. This is buried in the angular-datatables documentation. Here: https://l-lin.github.io/angular-datatables/#/api

The fix, frontend

app.controller('CidbClientsController', function($http, DTOptionsBuilder, DTColumnBuilder) {
    var vm = this;
    vm.dtOptions = DTOptionsBuilder.fromFnPromise(function() {
        return $http.get('/api/cidb/clients/read');
    }).withPaginationType('full_numbers').withDataProp('data'); // Add the withDataProp to let DT know to look at data vs aaData
 
    vm.dtColumns = [
        DTColumnBuilder.newColumn('client_id').withTitle('ID'),
        DTColumnBuilder.newColumn('name').withTitle('Name'),
        DTColumnBuilder.newColumn('original_date').withTitle('Original Date'),
        DTColumnBuilder.newColumn('contract_date').withTitle('Contract Date'),
        DTColumnBuilder.newColumn('status_id').withTitle('Status'),
        DTColumnBuilder.newColumn('account_current').withTitle('Account Current'),
    ];
 });

The fix, backend

And on my backend I needed to modify how I was returning the result so I changed my return from {object: array} to just array:

class ClientsRead(Resource):

     @jwt_required()
     def get(self):
         clients = CidbClients.query.all()
         client_list = []
         for c in clients:
             c = c.as_dict()
             client_list.append(c)
         return client_list # return a list of objects vs an object

Hopefully this will help somebody struggling with this issue somewhere else.

And for all of you skeptics seeing the @jwt_required() I bind my $httpProvider with the JWTtoken here:

app.config(function Config($httpProvider, jwtInterceptorProvider) {
         jwtInterceptorProvider.tokenGetter = function() {
             return sessionStorage.getItem('access_token');
         }
         $httpProvider.interceptors.push('jwtInterceptor');
     });

Write a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.