POST API Integration with Reactive Form & Routing
POST API is used to store data in database (db.json).
Where POST API Comes From
JSON Server already provides an inbuilt POST API.
We use /users endpoint with POST method.
Testing POST API with Thunder Client
Method: POST
URL:
http://localhost:3000/users
Body (JSON):
{
"name": "Test",
"age": 35,
"email": "test@test.com"
}
ID is auto-generated by JSON Server.
Status 201 means data is created successfully.
Creating Add User Component
Command:
ng g c components/add-user
This component is used to add a new user using a form.
Adding Routing
In app.routes.ts:
{
path: '',
component: UserListComponent
},
{
path: 'add',
component: AddUserComponent
}
Router Setup in App
In app.ts, import:
RouterOutlet, RouterLink
In app.html:
<ul>
<li><a routerLink="">User List</a></li>
<li><a routerLink="add">Add User</a></li>
</ul>
<router-outlet></router-outlet>
Add User Form (HTML)
add-user.component.html:
<h1>Add New User</h1>
<input placeholder="Enter Name" [formControl]="name" />
<br />
<input placeholder="Enter Email" [formControl]="email" />
<br />
<input placeholder="Enter Age" [formControl]="age" />
<br />
<button (click)="addUser()">Add User</button>
Form Controls (TS)
add-user.component.ts:
name = new FormControl('');
email = new FormControl('');
age = new FormControl('');
addUser() {
console.log(this.name.value, this.email.value, this.age.value);
}
ReactiveFormsModule must be imported.
POST API in User Service
user.service.ts:
saveUser(user: Users) {
return this.http.post<Users>(this.url, user);
}
Calling POST API from Component
addUser() {
if (this.name.value && this.email.value && this.age.value) {
const data: Users = {
name: this.name.value,
email: this.email.value,
age: Number(this.age.value)
};
this.userService.saveUser(data).subscribe(res => {
this.router.navigate(['']);
});
}
}
Router is used for redirection after user is added.
Why Redirect After POST
After adding a user, redirecting to user list helps confirm
that the new user is added successfully.