Bahria University, Lahore
Campus Department of Computer
Sciences Lab Journal 12=2
(Fall 2024)
Course: Introduction to Web Engineering Date:
Course Code: SEL 310 Max Marks: 15
Faculty’s Name: Abdul Mannan Lab Engineer: Abdul Mannan
Muhammad Hamza Nawaz
03-134221-055
Lab Objective
This lab demonstrates how to connect an Angular application to a Node.js server and
dynamically display data fetched from the server. The focus is on:
● Building a simple Node.js API to manage student information (in-memory storage, no
database).
● Fetching data from the API using Angular's HttpClient.
● Displaying the fetched data in the Angular application.
Tasks
Task 1: Set Up the Node.js Server
1. Create a Node.js server using Express.
2. Add an endpoint to fetch a list of students:
○ GET /students: Returns an array of student objects (e.g., { id, name, age,
grade }).
3. Add an endpoint to fetch a single student by ID:
○ GET /students id: Returns details of a student by ID or an error if the ID is
invalid.
4. Store the student data in an in-memory array.
CODE:
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();
const PORT = 5000;
app.use(cors()); // Enable CORS
app.use(bodyParser.json());
const users = [
{ userId: 1, fullName: 'Hamza Ali', age: 23, performance: 'A' },
{ userId: 2, fullName: 'Atif Khan', age: 24, performance: 'B' },
{ userId: 3, fullName: 'Haris Ahmed', age: 25, performance: 'C' }
];
app.get('/api/users', (req, res) => {
res.status(200).json(users);
});
app.get('/api/users/:userId', (req, res) => {
const id = parseInt(req.params.userId, 10);
const user = users.find(u => u.userId === id);
if (user) {
res.status(200).json(user);
} else {
res.status(404).json({ message: 'User not found' });
}
});
app.post('/api/users', (req, res) => {
const { fullName, age, performance } = req.body;
if (fullName && age && performance) {
const newUser = {
userId: users.length + 1,
fullName,
age,
performance
};
users.push(newUser);
res.status(201).json(newUser);
} else {
res.status(400).json({ message: 'Invalid user data' });
}
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Task 2: Set Up the Angular Application
1. Create a new Angular component: student-management.
2. Use Angular's HttpClientModule to enable HTTP requests.
Introduction to Web Engineering
3. Inject the HttpClient service into the student-management component.
CODE:
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, HttpClientModule],
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
studentsData: any[] = [];
fetchError: string | null = null;
constructor(private httpClient: HttpClient) { }
ngOnInit(): void {
this.loadStudentsData();
}
// Method to load student data
private loadStudentsData(): void {
this.httpClient.get<any[]>('http://localhost:6000/students')
.pipe(
catchError((error) => {
this.fetchError = 'Unable to fetch student data. Please try again later.';
console.error('Data Fetch Error:', error);
return of([]);
})
)
.subscribe({
next: (data) => this.studentsData = data,
error: (err) => console.error('Unexpected Error:', err),
complete: () => console.log('Student data fetch complete'),
});
}
}
Task 3: Fetch and Display Data
1. In the student-management component:
○ Call the Node.js server's /students endpoint using HttpClient.
○ Store the fetched student data in a variable.
2. Display the student data in an HTML table using Angular's *ngFor.
HTML CODE:
<div *ngIf="errorMessage; else studentTable">
<p>{{ errorMessage }}</p>
</div>
<ng-template #studentTable>
<table border="1" class="student-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Grade</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let student of students">
<td>{{ student.id }}</td>
<td>{{ student.name }}</td>
<td>{{ student.age }}</td>
<td>{{ student.grade }}</td>
</tr>
</tbody>
</table>
</ng-template>
Task 4: Add Error Handling
1. Handle server errors in Angular using RxJS catchError.
2. Display an error message if the API request fails.