Manoj Madushanka

Oct 14, 2020

3 min read

Angular CRUD with mock server

From this little article, I wanna share how to do crud operations using angular httpClient with a mock server.

First, create a new angular project using the below command(enable routing and style sheet as sass).

ng new project-name

so after we need to install JSON mock server using the below command

npm i -g json-server

after setup our dependencies we move to setup our json file this file act as a database in our mock server all crud operation will affect to this json file objects.below I pasted my json file and you need to save this file as .json format in your asset folder. (or somewhere else I recommend asset folder)

now we can test our mock server, for that redirect to your db.json file location and run below command.

json-server — watch db.json

when executing the above command we can see tree URL for each object in our json file and home URL.

using the home URL endpoint we can see other resources endpoint as well as below.

from this resource endpoint we can do any crud operation to out json object in our json file.

ok first step done now we know how to set up a mock server and now move to do crud operations using httpClient.

Before do get request lets to refresh httpClient get request ;)

it is observable then we need to subscribe it for reading values,

get reqest format : get(‘api-endpoint’,options:{headers:{},params:{}})

Then there are 6 steps for using angular httpClient,

  1. Import HttpClientModule in our app module.

2. Import HttpClient to our service.

first, we need to create a service using the below command

ng generate service post-service

3. Inject the HttpClient in the constructor of the service.

4. Implement the GET, POST, PUT, or DELETE method call.

5. Import the service into the required calling component class.

6. Call the method to make the Http request.

After we can list down our response data as below and finally we can run angular application and view results.

In the next step, I will implement other crud operations. Thank you I attached Github repos for further information.

mock-server reference: