JSON Server User API Integration - Service, Interface & HttpClient

Creating User List Component

Command used:

ng g c components/user-list

The component is created inside the components folder.


Creating User Service

Command used:

ng g s services/user

The service is created inside the services folder.


Using User List Component in App

User list component is imported in app.ts.

The selector is used in app.html.

Example:

<app-user-list></app-user-list>

Selector name is taken from the component TS file.


Calling API in User Service

HttpClient is imported and injected in the constructor.

A URL property is created for the JSON Server API.

JSON Server must be running.

Example:

constructor(private http: HttpClient) {}

url = 'http://localhost:3000/users';

getUsers() {
return this.http.get(this.url);
}


Creating User Interface

An interface file is created in the services folder.

Interface defines the structure of user data.

The interface is exported.

Example:

export interface Users {
id: number;
name: string;
age: number;
email: string;
}


Using Interface in Service

any type is replaced with the Users type.

Proper data typing is used instead of any.


Using Service in User List Component

User service is injected in the constructor.

A signal is created to store users data.

Example:

usersData = signal<Users[] | undefined>(undefined);

constructor(private userService: UserService) {}


Fetching Data on Component Load

ngOnInit lifecycle method is used.

Service method is called and subscribed.

Data is set into the signal.

Example:

ngOnInit() {
this.userService.getUsers().subscribe(data => {
this.usersData.set(data);
});
}


Displaying Users Data in HTML

User list title is added.

A loop is used to display users.

Signal value is accessed properly.

Example:


<h1>User List</h1>

<ul>
@for(user of usersData(); track user.id){
<ul class="user-ul">
<li> Name :{{user.name}}</li>
<li> Age :{{user.age}}</li>
<li> Email :{{user.email}}</li>
<li> id :{{user.id}}</li>

</ul>
}
</ul>


Styling the List

A class is added to the list.

Basic border and padding are applied using CSS.

Example:

.user-ul {
border-bottom: 1px solid #ddd;
padding: 10px;
}