It’s common to use APIs when working with external data sources on some features in Angular. However, you may occasionally work on a feature in parallel without immediate access to the database or API. Or, you might just be experimenting with ideas on a prototype. In such situations, you can fake a data source or mock the data to fulfill your immediate need and focus on your Angular project instead.
NEW RESEARCH: LEARN HOW DECISION-MAKERS ARE PRIORITIZING DIGITAL INITIATIVES IN 2024.
Letโs take an example feature โ You wish to display the names and additional information of your app’s users in their profile. However, you lack a database or an API.ย
There are several ways to mock the same results. We will discuss three such approaches in this blog:ย
- Using json-server
- Using Postman
- Mocking data with a simple JSON fileย ย ย ย
Your JSON Data
Here is an example of data that you might want to respond to from the app API:
{ "users": [ { "id": 1234, "name": "Andrew Owen", "age": 26, "eyeColor": "blue" }, { "id": 1235, "name": "Susan Que", "age": 45, "eyeColor": "hazel" }, { "id": 1236, "name": "John Doe", "age": 53, "eyeColor": "brown" } ], "admins": [ { "id": 1232, "name": "John Owen", "age": 53, "eyeColor": "brown" } ] }
Mocking with json-server
- Install json-serverย through npm. You don’t have to include it in the project file and add it to the package.json if it’s installed globally. We can run this separately without affecting the existing codebase.
npm install -g json-server
Or, you can install it locally within the project using the following command. This will save dependencies in your package.
ย npm install json-server --save-dev
- Then, create a new folder for the mock data. It can be a separate project folder or within your Angular application, depending on the previous step. Add the db.json file inside that new folder.
- Update your data in the db.json file. You can copy the above example to try it out.ย
- Then, you can add the following command to a package.json or run it directly.
json-server -- watch folder/db.json
- Visitย http://localhost:3000ย ย to verify ifย json-serverย is working. Under the Resources section, you should see all available APIs. Click on users to cross-check the data. You can later add more endpoints in the db.json as needed.
- By default, a simple CRUD operation is available for the included resources.
- Currently, you can add multiple resources in the same file for simple use cases. Itโs also possible to structure data into multiple files and folders, but making them work will require a few extra steps.ย
Itโs easy to get started withย json-server, and a basic requirement is a simple JSON file with data. There are also JavaScript libraries like MirageJS orย axios-mock-adapter for similar purposes.
Using Postman
Postman, which used to be a simple browser extension, is now a full-fledged API development toolkit. You can download it separately and install it on your system. To run the mock servers in Postman, we need an account and a workspace. The workspace allows you to easily share the mock server and other APIs with team members.
The mock feature allows you to specify the response data and then access that data from anywhere. You can also make your mock API private, protect it with a token, and set up additional headers in both requests and responses.
The first step is to create a mock server from the Postman interface.
Then, we can add request URLs along with the HTTP methods, response code, and response body for each endpoint. Letโs add /users with the following JSON as a response body.
{ "users": [ { "id": 1234, "name": "Andrew Owen", "age": 26, "eyeColor": "blue" }, { "id": 1235, "name": "Susan Que", "age": 45, "eyeColor": "hazel" }, { "id": 1236, "name": "John Doe", "age": 53, "eyeColor": "brown" } ], }
Then, click next and configure a few more options.
After creating a mock server, you will receive a URL to access them. You can also simulate the network delay and keep track of requests and responses over the period.
Consuming the Mock API in Angular Apps
- Generate a new service module with the following command. It will also generate a UserServiceย and itsย specย file.ย
$ ng g service User
- Add the following code in the user.service.ts.ย The URL i.e., http://localhost:3000 is here for simplicity. The usual practice is adding these config values in the environment and importing them here.
// src/app/user.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class UserService { url = 'http://localhost:3000'; constructor(private http: HttpClient) { } getUsers(): Observable { return this.http.get(this.url + '/users'); } }
- Then, in any component, you can import this service in the constructor and subscribe to the getUsers() method for all users.
// src/app/home/home.component.ts import { Component, OnInit } from '@angular/core'; import { UserService } from './../user.service'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'] }) export class HomeComponent implements OnInit { users = []; constructor(private userService: UserService) { } ngOnInit(): void { this.userService.getUsers().subscribe(data => { this.users = data.users }); } }
- Now, you can easily iterate over this user list in the template.
Mocking Data with JSON file
Instead of using other tools, itโs also possible to create a response object in the service itself and then pass these observable values to the component.
// src/app/user.service.ts import { Injectable } from '@angular/core' import { HttpClient } from '@angular/common/http' import { Observable } from 'rxjs' import { of } from 'rxjs' @Injectable({ providedIn: 'root' }) export class UserService { data = { users: [ { id: 1234, name: 'Andrew Owen', age: 26, eyeColor: 'blue' }, { id: 1235, name: 'Susan Que', age: 45, eyeColor: 'hazel' }, { id: 1236, name: 'John Doe', age: 53, eyeColor: 'brown' } ] } constructor (private http: HttpClient) {} getUsers (): Observable { return of(this.data.users) } }
Moreover, we can move the user data into a separate file, i.e.,ย user.json, and import it into the service file. For this, we need to enable theย resolveJsonModuleย in the compiler options inย tsconfig.ts.ย
// users.json { "users": [ { "id": 1234, "name": "Andrew Owen", "age": 26, "eyeColor": "blue" }, { "id": 1235, "name": "Susan Que", "age": 45, "eyeColor": "hazel" }, { "id": 1236, "name": "John Doe", "age": 53, "eyeColor": "brown" } ] }
//tsconfig.json { โฆ "compilerOptions": { โฆ "resolveJsonModule": true, } }
// src/app/user.service.ts import { Injectable } from '@angular/core' import { HttpClient } from '@angular/common/http' import { Observable } from 'rxjs' import { of } from 'rxjs' import * as usersData from './users.json' @Injectable({ providedIn: 'root' }) export class UserService { data = usersData constructor (private http: HttpClient) {} getUsers (): Observable { return of(this.data.users) }}
These were a few effective strategies to mock data in Angular applications. In part 2 of the post, we will explore using Angular mock services to develop without a backend. Subscribe to the Modus blog to receive your monthly newsletter.
We are also hiring Angular experts from all over the world. Check out the job openings at Modus Create.