Friday, April 9, 2021

Angular Backendless Development using Json-server

While working on Fronend project if backend APIs are not ready, developers can still start working using JSON Server and create mockApis to start. 


There are different ways to achieve this useful feature.



We have already discussed Custom Http interceptor by HttpClientModule approach in a different post.

This post is about how can we use json-server to mock the real back end. We need to install json-server, so that we can use it. Run below command to install this globally in your system.
npm install -g json-server
I am assuming you already have angular environment ready.
At this point decide on the data structure you are expecting as a result of the service call. Create a JSON file with some mock data.
//mockData.json
{
  "users": [
    {
      "id": 22,
      "fName": "Sourav",
      "lName": "Ganguly"
    },
    {
      "id": 10,
      "fName": "Sachin",
      "lName": "Tendulkar"
    }
  ]
}
Now run below command and check
json-server mockData.json
http://localhost:3000  //you will see this url in console
Open above url in any browser and see you will be able to see "/users" under "Resources" section. The user data can be accessible via http://localhost:3000/users url.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class UserService {
    url = "http://localhost:3000/users";
    constructor(private http: HttpClient) {}
    getUser(): Observable<any>{
        return this.url.get(this.url + '?_sort=id')
                    .map(response => response.json());
    }
}
We can apply sort/ filters/ search on the response data. There are lot of other features, check json-server for more information.

To use this cool feature we need to install this dependency, some developers don't want to use additional dependency, otherwise this is another easy way to implement fakebackend in AngularJS.

Thanks for reading. Feedback and comments are always welcome!!!

No comments:

Post a Comment