Using Json-server with Angular

Nipuni Sithara
2 min readJun 17, 2021

--

In angular instead of using a mock file to store data and work as a database, we can use ‘npm server’. This works as a backend.
It is a fake API and it can be used only for development. Useing this it can work with post, get, put and delete requests.
The setup is as follow.

1. Install it in to your project.
npm i json-server

2. Go to package.json file in your project and check in your dependencies it has already added.
“json-server”:”⁰.16.3"

3. In the “scipts” in that package.json file add son server. port 3000
“server”:”json-server — watch db.json — port 5000"
Generally json server runs on port 3000 and if you want you can change it as above.

4. Create db.json in your root folder or run following command and it will automatically create that file
npm run server

5. Now add your collection to db.json as following example.
{ “tasks”: [
{ “id”: 1,
“name”: “task 1”
},
{“id”: 2,
“name”: “task 2”
}}
Using those double quotations are essential.

6. Same as other API, it has to mention in your service file. To do that first import HttpClient as follow to service.
import {HttpClient} from ‘@angular/common/http’;
Remember to add it app.module.ts file too
import {HttpClientModule} from ‘@angular/common/http’;
And add it to ‘imports’ in same file.

7. In your service file declare a property to get url.
private url=http://localhost:5000/tasks"
After that add that property to constructor as an argument.
constructor(private http:HttpClient)

Now you can use http requests using npm server.

--

--