How to display REST Service Data with UI Grid

In this article we will show how to use the UI Grid Component with AngularJS to display an editable grid. The back end of our UI Grid will be a REST Service running on WildFly application Server.

If you are new to using AngularJS with REST Services we recommend checking this article: Develop a REST application using Jakarta EE and AngularJS

That being said, in the next section we will briefly introduce the REST Endpoint and then we will create some simple and more advanced UI Grid to display the Data in Tabular format.

Step 1: The REST Endpoint

This is our server REST Service which contains the standard CRUD methods to perform Create, Read, Update and Delete Operations on the Customer Entity:

@Path("customers")
@ApplicationScoped
@Produces("application/json")
@Consumes("application/json")
public class CustomerEndpoint {

    @Inject CustomerRepository customerRepository;

    @GET
    public List<Customer> getAll() {
        return customerRepository.findAll();
    }

    @POST
    public Response create(Customer customer) {

        Customer c =  customerRepository.createCustomer(customer);
        return Response.status(201).entity(customer).build();
    }
    
    @PUT
    public Response update(Customer customer) {
        System.out.println("Called update for "+customer);
        customerRepository.updateCustomer(customer);         
        return Response.status(204).build();
    }
    @DELETE
    public Response delete(@QueryParam("id") Long customerId) {
        customerRepository.deleteCustomer(customerId);
        return Response.status(204).build();
    }

}

And here is the Customer JPA Entity we will display in the UI Grid:

@Entity
@NamedQuery(name = "Customers.findAll",
        query = "SELECT c FROM Customer c ORDER BY c.id")
public class Customer {
    @Id
    @SequenceGenerator(
            name = "customerSequence",
            sequenceName = "customerId_seq",
            allocationSize = 1,
            initialValue = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "customerSequence")
    private Long id;
    @Column(length = 40)
    private String name;
    @Column(length = 40)
    private String surname;
 
    // Getters/Setters omitted for brevity   
}

Coding the Front End

To use UI Grid with AngularJS you need to link the following libraries in your HTML page:

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-grid/4.10.0/ui-grid.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-grid/4.10.0/ui-grid.min.css" type="text/css" />
</head>

Then, in the body of your page, include the AngularJS Controller with the following functions:

<body>
    <div ng-controller="CustomerController">
      <div ui-grid="gridOptions" class="grid"></div>
    </div> 

    <script>
// Define your AngularJS app module
var app = angular.module('myApp', ['ui.grid']);

// Create a controller for the customer data
app.controller('CustomerController', function($scope, $http) {
  $scope.gridOptions = {
    columnDefs: [
      { name: 'id', displayName: 'ID' },
      { name: 'name', displayName: 'Name' },
      { name: 'surname', displayName: 'Surname' }
    ],
    enableGridMenu: true,
    enableSorting: true,
    enableFiltering: true
  };

  // Fetch customer data from the REST service
  $http.get('rest/customers')
    .then(function(response) {
      $scope.gridOptions.data = response.data;
    })
    .catch(function(error) {
      console.error('Error retrieving customer data:', error);
    });
});

    </script>

</body>
</html>

By deploying the above grid.html page, you will be able to see the data in Tabular Format as in this snapshot:

UI Grid Angular JS Java

An Advanced UI Grid

In the following example, we will add more functionalities to our UI Grid. We will add an “Add Button” button which will allow us to insert a new Entity. Also, we will add a Delete button to delete an Entity from the Grid.

Here is the grid2.html page:

<body>
  <div ng-controller="CustomerController">
    <div>
      <input type="text" ng-model="newName" placeholder="Name">
      <input type="text" ng-model="newSurname" placeholder="Surname">
      <button class="btn btn-primary" ng-click="addCustomer()">Add Customer</button>
    </div>
    <div ui-grid="gridOptions" class="grid"></div>
  </div>
 
  

    <script>

// Define your AngularJS app module
var app = angular.module('myApp', ['ui.grid']);

// Create a controller for the customer data
app.controller('CustomerController', function($scope, $http) {
  $scope.gridOptions = {
    columnDefs: [
      { name: 'id', displayName: 'ID' },
      { name: 'name', displayName: 'Name' },
      { name: 'surname', displayName: 'Surname' },
      {
        name: 'actions',
        displayName: 'Actions',
        cellTemplate:
          '<div class="ui-grid-cell-contents">' +
          '  <button class="btn btn-primary btn-xs" ng-click="grid.appScope.deleteCustomer(row.entity.id)">Delete</button>' +
          '</div>'
      }
    ],
    enableGridMenu: true,
    enableSorting: true,
    enableFiltering: true
  };

  // Fetch customer data from the REST service
  $http.get('rest/customers')
    .then(function(response) {
      $scope.gridOptions.data = response.data;
    })
    .catch(function(error) {
      console.error('Error retrieving customer data:', error);
    });

  // Function to add a new customer
  $scope.addCustomer = function() {
    var newCustomer = {
      name: $scope.newName,
      surname: $scope.newSurname
    };

    $http.post('rest/customers', newCustomer)
      .then(function(response) {
        $scope.gridOptions.data.push(response.data);
        $scope.newName = '';
        $scope.newSurname = '';
      })
      .catch(function(error) {
        console.error('Error adding customer:', error);
      });
  };

  // Function to delete a customer
  $scope.deleteCustomer = function(customerId) {
    $http.delete('rest/customers?id=' + customerId)
      .then(function() {
        var index = $scope.gridOptions.data.findIndex(function(customer) {
          return customer.id === customerId;
        });

        if (index !== -1) {
          $scope.gridOptions.data.splice(index, 1);
        }
      })
      .catch(function(error) {
        console.error('Error deleting customer:', error);
      });
  };
});



    </script>

</body>
</html>

Here is the new UI Grid when you deploy the application:

UI grid with REST Service example

Conclusion

In conclusion, this tutorial has provided a comprehensive guide on utilizing AngularJS and UI Grid to present REST data in a tabular format. By following the step-by-step instructions, developers can leverage the power of AngularJS to create dynamic and interactive web applications.

Source code: https://github.com/fmarchioni/mastertheboss/tree/master/jax-rs/angular

Found the article helpful? if so please follow us on Socials