Creating Generic Restful Services in Angular

This is the first part of the series to create generic components in angular. In order to see all the articles please visit this link.

Generic Angular Component Series:
Part 1: Creating Generic Restful Services in Angular
Part 2: Creating Generic Table in Angular Material Design
Part 3: Creating CRUD table based on Restful APIs in Angular [In Prorgress]

The first step towards leveraging generics and creating reusable code and components is to start at the bottom-most layer, aka Service Layer. Let's see how one can create a generic service.

Step 1: Create the Read, Update, and Create Models for which the service is being built.

Step 2: Collect the input parameters that will be required to pass into the service, e.g: endpoint to call, API version, headers, query parameters, etc.

Once we have narrowed down the requirements its time to get into action and write some code.

Base CRUD Service

P.S: If the contract and model change between API versions, then its better to abstract away the API version from the Base Service and in fact create different versions of the service itself, with each of them extending the base service itself.

Since now we have the basic structure for the service lets start off by creating some Models.

Let's start off with the famous Todo Items and see how can we model it. First, refine the model as follow, and this basically should be in sync with the API contracts itself. Once, we have the base abstract service and the respective data models, we are all set to create the Todo Service. :)

Todo Item data models and service

Now that we have the models and services defined, we can easily declare the service in the module and then inject it accordingly. Note that the procedure for a new service is the same as this one, and additionally once could override the methods of the base service at will.

NOTE: Next article will be published soon, and meanwhile work is being done to create a git repo for a functioning application.

--

--