Angular CRUD with mock server

Manoj Madushanka
3 min readOct 14, 2020

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)

{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
current file structure

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

mock server started successfully

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.

mock server homepage

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.
import HttpClientModule

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.

inject HttpClient in service class

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

get method implementation

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

import service into a component class

6. Call the method to make the Http request.

call mock server get post method to get a post JSON object

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

list down post title
final result of get endpoint

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

mock-server reference: https://github.com/typicode/json-server

project-repo: https://github.com/manoj1995madushanka/httpClientMockAngular

--

--