0% found this document useful (0 votes)
72 views48 pages

AngularJS and Node.js Code Examples

The document contains multiple code snippets demonstrating the use of AngularJS and Node.js for various tasks. It includes examples of creating AngularJS applications for addition, displaying bank details, and fetching data from APIs, as well as Node.js applications for reading files asynchronously and implementing Express.js routes for CRUD operations. Each section provides specific code implementations and explanations for the respective functionalities.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views48 pages

AngularJS and Node.js Code Examples

The document contains multiple code snippets demonstrating the use of AngularJS and Node.js for various tasks. It includes examples of creating AngularJS applications for addition, displaying bank details, and fetching data from APIs, as well as Node.js applications for reading files asynchronously and implementing Express.js routes for CRUD operations. Each section provides specific code implementations and explanations for the respective functionalities.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SLIP 1

Q.1) Write an AngularJS script for addition of two numbers using ng-init, ng-model & ng-bind. And also
demonstrate ng-show, ng-disabled, ng-click directives on button component.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Addition of Two Numbers in AngularJS</title>

<script src="[Link]

</head>

<body ng-app="additionApp" ng-controller="AdditionController" ng-init="num1=0; num2=0; result=0;


showResult=false">

<h2>Addition of Two Numbers</h2>

<!-- Input fields for the numbers with ng-model -->

<label for="num1">Enter first number:</label>

<input type="number" id="num1" ng-model="num1" required>

<br>

<label for="num2">Enter second number:</label>

<input type="number" id="num2" ng-model="num2" required>

<br><br>

<!-- Button with ng-click to trigger addition, ng-disabled if inputs are empty -->

<button ng-click="addNumbers()" ng-disabled="!num1 || !num2">Add Numbers</button>

<!-- Display result only when showResult is true using ng-show -->
<h3 ng-show="showResult">Result: <span ng-bind="result"></span></h3>

<script>

// Define AngularJS module and controller

[Link]('additionApp', [])

.controller('AdditionController', function($scope) {

// Function to add numbers and display result

$[Link] = function() {

$[Link] = parseFloat($scope.num1) + parseFloat($scope.num2);

$[Link] = true;

};

});

</script>

</body>

</html>

Q.2) Create a [Link] application that reads data from multiple files asynchronously using promises and
async/await.

const fs = require('fs').promises;

async function readFiles(filePaths) {

try {

// Read multiple files asynchronously using [Link]

const fileReadPromises = [Link](path => [Link](path, 'utf-8'));

const fileContents = await [Link](fileReadPromises);

// Log each file's content

[Link]((content, index) => {

[Link](`Content of file ${filePaths[index]}:\n${content}\n`);


});

} catch (error) {

[Link]("Error reading files:", error);

// Example file paths (replace with actual paths)

const files = ['./[Link]', './[Link]', './[Link]'];

// Call the function to read files

readFiles(files);

SLIP2

Write an AngularJS script to print details of bank (bank name, MICR code, IFC code, address etc.) in
tabular form using ng-repeat.

//html file

<!DOCTYPE html>

<html ng-app="bankApp">

<head>

<title>Bank Details</title>

<script src="[Link]

<script src="[Link]"></script>

</head>

<body ng-controller="BankController">

<h2>Bank Details</h2>

<table border="1">

<thead>
<tr>

<th>Bank Name</th>

<th>MICR Code</th>

<th>IFSC Code</th>

<th>Address</th>

</tr>

</thead>

<tbody>

<!-- ng-repeat to iterate over each bank object -->

<tr ng-repeat="bank in banks">

<td>{{ [Link] }}</td>

<td>{{ [Link] }}</td>

<td>{{ [Link] }}</td>

<td>{{ [Link] }}</td>

</tr>

</tbody>

</table>

</body>

</html>

//angularJs file

// Define AngularJS application

var app = [Link]('bankApp', []);

// Define controller

[Link]('BankController', function($scope) {

// List of banks

$[Link] = [

{
name: 'Bank of America',

micrCode: '123456789',

ifscCode: 'BOFA12345',

address: '123 Main St, New York, NY'

},

name: 'Wells Fargo',

micrCode: '987654321',

ifscCode: 'WF123456',

address: '456 Elm St, San Francisco, CA'

},

name: 'Chase Bank',

micrCode: '543216789',

ifscCode: 'CHAS09876',

address: '789 Maple Ave, Chicago, IL'

];

});

Create a simple Angular application that fetches data from an API using HttpClient.
Implement an Observable to fetch data from an API endpoint.
// src/app/[Link]
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
providedIn: 'root'
})
export class DataService {
private apiUrl = '[Link] // Sample API

constructor(private http: HttpClient) { }

// Method to fetch data from the API


getData(): Observable<any> {
return [Link]([Link]);
}
}
Slip 3
Write an AngularJS script to display list of games stored in an array on click of button using ng-click
and also demonstrate ng-init, ng-bind directive of AngularJS

<!DOCTYPE html>
<html ng-app="gameApp">
<head>
<title>Game List Display</title>
<script
src="[Link]
</head>
<body ng-controller="GameController" ng-init="isListVisible=false">

<h1>Game List</h1>

<!-- Button to show the list of games -->


<button ng-click="showGames()">Show Games</button>
<!-- Display a message when the list is empty -->
<p ng-if="![Link]">No games to display</p>

<!-- Display the list of games -->


<ul ng-if="isListVisible">
<li ng-repeat="game in games" ng-bind="game"></li>
</ul>

<script>
// Define the AngularJS application module
[Link]('gameApp', [])
.controller('GameController', function($scope) {
// Initialize the list of games
$[Link] = ['Chess', 'Monopoly', 'Scrabble', 'Risk'];

// Function to show the list of games


$[Link] = function() {
$[Link] = true;
};
});
</script>
</body>
</html>

Find a company with a workforce greater than 30 in the array (use find by id
method)

type Company = {
id: number;
name: string;
workforce: number;
};

const companies: Company[] = [


{ id: 1, name: "TechCorp", workforce: 25 },
{ id: 2, name: "InnovateInc", workforce: 40 },
{ id: 3, name: "BuildIt", workforce: 15 },
{ id: 4, name: "DevelopHub", workforce: 35 },
];

const companyWithLargeWorkforce = [Link](company =>


[Link] > 30);

[Link](companyWithLargeWorkforce);

SLIP 4
Fetch the details using ng-repeat in AngularJS

<div ng-app="myApp" ng-controller="CompanyController">


<ul>
<li ng-repeat="company in companies | filter: filterByWorkforce">
<strong>ID:</strong> {{ [Link] }} <br>
<strong>Name:</strong> {{ [Link] }} <br>
<strong>Workforce:</strong> {{ [Link] }}
<hr>
</li>
</ul>
</div>
var app = [Link]('myApp', []);
[Link]('CompanyController', function($scope) {
$[Link] = [
{ id: 1, name: "TechCorp", workforce: 25 },
{ id: 2, name: "InnovateInc", workforce: 40 },
{ id: 3, name: "BuildIt", workforce: 15 },
{ id: 4, name: "DevelopHub", workforce: 35 }
];

$[Link] = function(company) {
return [Link] > 30;
};
});
[Link] application to include middleware for parsing request bodies (e.g., JSON, form data) and
validating input data.

const express = require('express');


const { body, validationResult } = require('express-validator');
const app = express();
const PORT = 3000;

// Middleware to parse JSON and form data


[Link]([Link]());
[Link]([Link]({ extended: true }));

// Sample route with validation middleware


[Link](
'/submit',
// Validation middleware
[
body('name').isString().withMessage('Name must be a
string').notEmpty().withMessage('Name is required'),
body('email').isEmail().withMessage('Invalid email address'),
body('age').isInt({ min: 1 }).withMessage('Age must be a positive
integer'),
],
(req, res) => {
// Check for validation errors
const errors = validationResult(req);
if (![Link]()) {
return [Link](400).json({ errors: [Link]() });
}

// Process the request if validation passes


const { name, email, age } = [Link];
[Link](200).json({ message: 'Data received successfully', data: {
name, email, age } });
}
);

// Start the server


[Link](PORT, () => {
[Link](`Server is running on [Link]
});

SLIP5
Create a simple Angular component that takes input data and displays it.

import { Component, Input } from '@angular/core';

@Component({
selector: 'app-display-item',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class DisplayItemComponent {
@Input() item: string = ''; // Input property to accept data from
parent
}
<div *ngIf="item">
<p>{{ item }}</p>
</div>
<app-display-item [item]="'Hello, Angular!'"></app-display-item>

Implement a simple server using [Link]

const http = require('http');

// Define the port the server will listen on


const PORT = 3000;

// Create the server


const server = [Link]((req, res) => {
// Set the response header content type
[Link](200, { 'Content-Type': 'text/plain' });

// Send a response message


[Link]('Hello, World!\n');
});

// Start the server


[Link](PORT, () => {
[Link](`Server is running at [Link]
});

SLIP 6
Develop an [Link] application that defines routes for Create and Read operations on a resource
(products).

const express = require('express');


const app = express();
const PORT = 3000;

// Middleware to parse incoming JSON requests


[Link]([Link]());

// Sample in-memory data to store products


let products = [
{ id: 1, name: 'Product 1', price: 100 },
{ id: 2, name: 'Product 2', price: 150 },
];
// Route for creating a new product (POST)
[Link]('/products', (req, res) => {
const { name, price } = [Link];

// Basic validation
if (!name || !price) {
return [Link](400).json({ message: 'Name and price are
required' });
}

const newProduct = {
id: [Link] + 1, // Simple auto-increment logic
name,
price,
};

[Link](newProduct);
[Link](201).json(newProduct); // Send the new product as
response
});

// Route for getting all products (GET)


[Link]('/products', (req, res) => {
[Link](200).json(products); // Return the list of products
});

// Route for getting a single product by id (GET)


[Link]('/products/:id', (req, res) => {
const productId = parseInt([Link]);
const product = [Link](p => [Link] === productId);

if (!product) {
return [Link](404).json({ message: 'Product not found' });
}

[Link](200).json(product); // Return the found product


});

// Start the server


[Link](PORT, () => {
[Link](`Server is running on [Link]
});
Find a company with a workforce greater than 30 in the array. (Using find by id method)

const companies = [

{ id: 1, name: 'Company A', workforce: 25 },

{ id: 2, name: 'Company B', workforce: 35 },

{ id: 3, name: 'Company C', workforce: 50 },

{ id: 4, name: 'Company D', workforce: 20 },

];

const companyIdToSearch = 2; // The id of the company we're looking for

// Use the `find` method to locate the company with the given id and workforce > 30

const company = [Link](company => [Link] === companyIdToSearch &&


[Link] > 30);

if (company) {

[Link](`Found company: ${[Link]}, Workforce: ${[Link]}`);

} else {

[Link]('No company found with the specified id and workforce greater than 30.');

SLIP7

Create a [Link] application that reads data from multiple files asynchronously using promises and
async/await.

const fs = require('fs').promises; // Using promises-based fs module

const path = require('path');

// List of files to read

const files = [

[Link](__dirname, 'data', '[Link]'),


[Link](__dirname, 'data', '[Link]'),

[Link](__dirname, 'data', '[Link]')

];

// Function to read files asynchronously using async/await

async function readFiles() {

try {

const fileContents = await [Link]([Link](async (filePath) => {

const content = await [Link](filePath, 'utf8'); // Read file content asynchronously

return content;

}));

// Print the contents of the files

[Link]((content, index) => {

[Link](`Content of file${index + 1}:`);

[Link](content);

[Link]('---');

});

} catch (error) {

[Link]('Error reading files:', error);

// Call the function to read files

readFiles();

Develop an [Link] application that defines routes for Create and Read operations on a resource
(User).

const express = require('express');


const app = express();

const PORT = 3000;

// Middleware to parse JSON bodies

[Link]([Link]());

// In-memory database (Array of users) - This will be used to store users

let users = [

{ id: 1, name: 'Alice', email: 'alice@[Link]' },

{ id: 2, name: 'Bob', email: 'bob@[Link]' },

];

// Route to create a new user (POST request)

[Link]('/users', (req, res) => {

const { name, email } = [Link];

// Basic validation

if (!name || !email) {

return [Link](400).json({ message: 'Name and email are required' });

// Create a new user and add it to the in-memory "database"

const newUser = {

id: [Link] + 1, // Simple auto-increment logic for ID

name,

email,

};

[Link](newUser);
// Respond with the newly created user

[Link](201).json(newUser);

});

// Route to get all users (GET request)

[Link]('/users', (req, res) => {

[Link](200).json(users); // Return the list of users

});

// Route to get a single user by ID (GET request)

[Link]('/users/:id', (req, res) => {

const userId = parseInt([Link]);

const user = [Link](u => [Link] === userId);

if (!user) {

return [Link](404).json({ message: 'User not found' });

[Link](200).json(user); // Return the found user

});

// Start the server

[Link](PORT, () => {

[Link](`Server is running at [Link]

});
SLIP 8

Create a simple Angular application that fetches data from an API using HttpClient. Implement an
Observable to fetch data from an API endpoint.

import { NgModule } from '@angular/core';

import { BrowserModule } from '@angular/platform-browser';

import { HttpClientModule } from '@angular/common/http'; // Import HttpClientModule

import { AppComponent } from './[Link]';

@NgModule({

declarations: [AppComponent],

imports: [

BrowserModule,

HttpClientModule // Add HttpClientModule to imports

],

providers: [],

bootstrap: [AppComponent]

})

export class AppModule {}

import { Injectable } from '@angular/core';

import { HttpClient } from '@angular/common/http';

import { Observable } from 'rxjs';

@Injectable({

providedIn: 'root'

})

export class ApiService {

private apiUrl = '[Link] // Example API


constructor(private http: HttpClient) {}

getPosts(): Observable<any[]> {

return [Link]<any[]>([Link]);

Develop an [Link] application that defines routes for Create, Update operations on a resource
(Employee).

const express = require('express');

const bodyParser = require('body-parser');

const app = express();

const port = 3000;

// Middleware to parse JSON bodies

[Link]([Link]());

// In-memory "database" for storing employees

let employees = [];

// Route to create a new employee

[Link]('/employee', (req, res) => {

const { id, name, position, salary } = [Link];

if (!id || !name || !position || !salary) {

return [Link](400).json({ error: 'Missing required fields' });

}
// Check if employee with the given ID already exists

const existingEmployee = [Link](emp => [Link] === id);

if (existingEmployee) {

return [Link](400).json({ error: 'Employee with this ID already exists' });

const newEmployee = { id, name, position, salary };

[Link](newEmployee);

[Link](201).json(newEmployee);

});

// Route to update an existing employee by ID

[Link]('/employee/:id', (req, res) => {

const { id } = [Link];

const { name, position, salary } = [Link];

const employeeIndex = [Link](emp => [Link] === id);

if (employeeIndex === -1) {

return [Link](404).json({ error: 'Employee not found' });

// Update the employee details

employees[employeeIndex] = {

id,

name: name || employees[employeeIndex].name,

position: position || employees[employeeIndex].position,

salary: salary || employees[employeeIndex].salary,


};

[Link](employees[employeeIndex]);

});

// Start the server

[Link](port, () => {

[Link](`Server is running on [Link]

});

SLIP 9

Find a company with a workforce greater than 30 in the array. (Using find by id method).

interface Company {
id: number;
name: string;
workforce: number;
}

const companies: Company[] = [


{ id: 1, name: 'Company A', workforce: 50 },
{ id: 2, name: 'Company B', workforce: 20 },
{ id: 3, name: 'Company C', workforce: 60 },
{ id: 4, name: 'Company D', workforce: 10 },
];

// Finding a company with workforce greater than 30


const companyWithLargeWorkforce = [Link](company =>
[Link] > 30);

if (companyWithLargeWorkforce) {
[Link](`Company with workforce greater than 30:
${[Link]}`);
} else {
[Link]('No company with workforce greater than 30 was
found.');
}

) Create [Link] application to include middleware for parsing request bodies (e.g., JSON, form data)
and validating input data. Send appropriate JSON responses for success and error cases.

import express, { Request, Response, NextFunction } from 'express';


import { body, validationResult } from 'express-validator';
import bodyParser from 'body-parser';

const app = express();

// Middleware to parse JSON and URL-encoded data


[Link]([Link]());
[Link]([Link]({ extended: true }));

// Route to handle form submission (POST)


[Link](
'/submit',
// Input validation middleware
body('name').isString().withMessage('Name must be a string'),
body('age').isInt({ min: 18 }).withMessage('Age must be an integer
and at least 18'),
(req: Request, res: Response, next: NextFunction) => {
// Check if there are validation errors
const errors = validationResult(req);
if (![Link]()) {
return [Link](400).json({
success: false,
errors: [Link](),
});
}
next();
},
(req: Request, res: Response) => {
// If no validation errors, process the request data
const { name, age } = [Link];
[Link]({
success: true,
message: 'Form submitted successfully!',
data: { name, age },
});
}
);

// Middleware to handle 404 errors (in case of invalid routes)


[Link]((req: Request, res: Response) => {
[Link](404).json({
success: false,
message: 'Not Found',
});
});

// Start the Express server


const PORT = 3000;
[Link](PORT, () => {
[Link](`Server running on port ${PORT}`);
});
SLIP 10
Implement a simple server using [Link].

// Import the http module


const http = require('http');

// Define the server


const server = [Link]((req, res) => {
// Set the response header to indicate content type
[Link](200, { 'Content-Type': 'text/plain' });

// Write a response message


[Link]('Hello, World!\n');
});

// Define the port and host for the server


const port = 3000;
const host = 'localhost';

// Start the server and listen on the specified host and port
[Link](port, host, () => {
[Link](`Server running at [Link]
});
Extend the previous [Link] application to include middleware for parsing request bodies (e.g., JSON,
form data) and validating input data. Send appropriate JSON responses for success and error cases.

const express = require('express');


const bodyParser = require('body-parser');
const { body, validationResult } = require('express-validator');

const app = express();

// Middleware to parse JSON and URL-encoded data


[Link]([Link]()); // for application/json
[Link]([Link]({ extended: true })); // for
application/x-www-form-urlencoded

// Example route with validation


[Link]('/user', [
// Validate and sanitize input
body('username').isLength({ min: 3 }).withMessage('Username must
be at least 3 characters long'),
body('email').isEmail().withMessage('Please provide a valid email
address'),
body('password').isLength({ min: 6 }).withMessage('Password must
be at least 6 characters long')
], (req, res) => {
// Check for validation errors
const errors = validationResult(req);
if (![Link]()) {
return [Link](400).json({ errors: [Link]() });
}

// Handle valid data


const { username, email, password } = [Link];
[Link](200).json({
message: 'User created successfully',
data: { username, email }
});
});

// Example of an endpoint that would handle a GET request


[Link]('/', (req, res) => {
[Link](200).json({
message: 'Welcome to the API'
});
});

// Global error handler (optional)


[Link]((err, req, res, next) => {
[Link]([Link]);
[Link](500).json({ message: 'Something went wrong!' });
});

// Start the server


const port = 3000;
[Link](port, () => {
[Link](`Server is running on port ${port}`);
});

SLIP11
Develop an [Link] application that defines routes for Create operations on a resource (Movie).

const express = require('express');


const bodyParser = require('body-parser');

// Initialize the Express app


const app = express();

// Middleware to parse incoming request bodies


[Link]([Link]());

// Sample in-memory movie database (you can replace it with a real


database like MongoDB or MySQL later)
const movies = [];

// Create movie route (POST)


[Link]('/movies', (req, res) => {
const { title, director, releaseYear, genre } = [Link];

// Validation (you can extend this as per requirements)


if (!title || !director || !releaseYear || !genre) {
return [Link](400).json({ error: 'All fields (title, director,
releaseYear, genre) are required.' });
}

// Create a new movie object


const newMovie = { id: [Link] + 1, title, director,
releaseYear, genre };

// Save the new movie


[Link](newMovie);

// Respond with the newly created movie


[Link](201).json(newMovie);
});
// Start the server
const PORT = 3000;
[Link](PORT, () => {
[Link](`Server running on [Link]
});

Create Angular application that print the name of students who play basketball using filter and map
method.

import { Component, OnInit } from '@angular/core';

@Component({
selector: 'app-basketball',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class BasketballComponent implements OnInit {

students = [
{ name: 'John', playsBasketball: true },
{ name: 'Jane', playsBasketball: false },
{ name: 'Tom', playsBasketball: true },
{ name: 'Lucy', playsBasketball: false },
{ name: 'Alex', playsBasketball: true }
];

basketballPlayers: string[] = [];

constructor() { }

ngOnInit(): void {
[Link]();
}

filterAndMapBasketballPlayers() {
[Link] = [Link]
.filter(student => [Link]) // Filters students who
play basketball
.map(student => [Link]); // Maps to an array of names of
those students
}

}
<div>
<h2>Students Who Play Basketball</h2>
<ul>
<li *ngFor="let player of basketballPlayers">{{ player }}</li>
</ul>
</div>

SLIP12
Write an AngularJS script to print details of Employee (employee name, employee Id,Pin code, address
etc.) in tabular form using ng-repeat.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Employee Details</title>
<script
src="[Link]
[Link]"></script>
</head>
<body ng-app="employeeApp" ng-controller="EmployeeController">

<h1>Employee Details</h1>

<table border="1">
<thead>
<tr>
<th>Employee Name</th>
<th>Employee ID</th>
<th>Pin Code</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="employee in employees">
<td>{{ [Link] }}</td>
<td>{{ [Link] }}</td>
<td>{{ [Link] }}</td>
<td>{{ [Link] }}</td>
</tr>
</tbody>
</table>

</body>
</html>
// Define the AngularJS module and controller
[Link]('employeeApp', [])
.controller('EmployeeController', function($scope) {
// Define the list of employee details
$[Link] = [
{ name: 'John Doe', id: 'E001', pinCode: '12345', address: '1234 Elm
Street' },
{ name: 'Jane Smith', id: 'E002', pinCode: '67890', address: '5678
Oak Avenue' },
{ name: 'Mark Johnson', id: 'E003', pinCode: '11223', address: '9101
Pine Road' },
{ name: 'Sarah Williams', id: 'E004', pinCode: '44556', address:
'1112 Maple Lane' }
];
});

Develop an [Link] application that defines routes for Create operations on a resource (User).

// [Link]
const express = require('express');
const bodyParser = require('body-parser');

const app = express();


const port = 3000;

// Middleware to parse JSON request bodies


[Link]([Link]());

// In-memory data storage for users


let users = [];

// Route to create a new user (POST /users)


[Link]('/users', (req, res) => {
const { name, email } = [Link];

// Validate that name and email are provided


if (!name || !email) {
return [Link](400).json({ message: 'Name and email are
required' });
}

// Create a new user object


const newUser = { id: [Link] + 1, name, email };

// Add the new user to the users array


[Link](newUser);

// Return the created user with a 201 status


return [Link](201).json(newUser);
});
// Route to get all users (GET /users) - just for testing purposes
[Link]('/users', (req, res) => {
[Link](200).json(users);
});

// Start the server


[Link](port, () => {
[Link](`Server running on [Link]
});

SLIP13
Extend the previous [Link] application to include middleware for parsing request bodies (e.g., JSON,
form data) and validating input data. Send appropriate JSON responses for success and error cases.

const express = require('express');


const Joi = require('joi');
const app = express();

// Middleware to parse JSON and form data


[Link]([Link]()); // for parsing application/json
[Link]([Link]({ extended: true })); // for parsing
application/x-www-form-urlencoded
// Define a simple route that expects some input data (e.g., username
and email)
[Link]('/submit', (req, res) => {
// Validation schema using Joi
const schema = [Link]({
username: [Link]().min(3).max(30).required().messages({
'[Link]': 'Username should be a string',
'[Link]': 'Username should be at least 3 characters long',
'[Link]': 'Username should not be longer than 30 characters',
'[Link]': 'Username is required',
}),
email: [Link]().email().required().messages({
'[Link]': 'Please provide a valid email address',
'[Link]': 'Email is required',
}),
});

// Validate request data


const { error, value } = [Link]([Link]);

if (error) {
// If validation fails, return an error response with details
return [Link](400).json({
success: false,
message: 'Validation error',
details: [Link](detail => [Link]),
});
}

// If validation succeeds, proceed with the logic


return [Link](200).json({
success: true,
message: 'Data successfully received',
data: value, // Send the valid input data back
});
});

// Default route
[Link]('/', (req, res) => {
[Link]('Welcome to the [Link] app!');
});

// Start server
const PORT = [Link] || 3000;
[Link](PORT, () => {
[Link](`Server running on port ${PORT}`);
});

Create a simple Angular component that takes input data and displays it.

import { Component, Input } from '@angular/core';

@Component({
selector: 'app-display-data',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class DisplayDataComponent {
@Input() data: string = ''; // Input property to accept data
<div>
<p>Data received: {{ data }}</p>
</div>}

SLIP 14
Create Angular application that print the name of students who got 85% using filter and map method.

import { Component, OnInit } from '@angular/core';


@Component({
selector: 'app-student-list',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class StudentListComponent implements OnInit {
students = [
{ name: 'John', score: 90 },
{ name: 'Jane', score: 78 },
{ name: 'Jake', score: 85 },
{ name: 'Sara', score: 92 },
{ name: 'Tom', score: 80 }
];

filteredStudentNames: string[] = [];

ngOnInit(): void {
// Filter students who scored 85% or more and map to their names
[Link] = [Link]
.filter(student => [Link] >= 85) // Filter students by score
.map(student => [Link]); // Map the filtered students
to their names
}
}

Develop an [Link] application that defines routes for Create, Update operations on a resource
(Employee).

const express = require('express');


const app = express();
const port = 3000;

// Middleware to parse JSON request bodies


[Link]([Link]());

// In-memory database (just for demo purposes)


let employees = [
{ id: 1, name: 'Alice', position: 'Developer' },
{ id: 2, name: 'Bob', position: 'Manager' }
];

// Create an employee
[Link]('/employees', (req, res) => {
const { name, position } = [Link];
// Validate the request body
if (!name || !position) {
return [Link](400).json({ error: 'Name and position are
required.' });
}

const newEmployee = {
id: [Link] + 1,
name,
position
};

[Link](newEmployee);
[Link](201).json(newEmployee);
});

// Update an employee
[Link]('/employees/:id', (req, res) => {
const employeeId = parseInt([Link]);
const { name, position } = [Link];

// Find the employee by ID


const employee = [Link](emp => [Link] === employeeId);

if (!employee) {
return [Link](404).json({ error: 'Employee not found.' });
}

// Update the employee's data


if (name) [Link] = name;
if (position) [Link] = position;

[Link](employee);
});

// Start the server


[Link](port, () => {
[Link](`Server running at [Link]
});

SLIP 15
Find an emp with a Salary greater than 25000 in the array. (Using find by id method)

const employees = [
{ id: 1, name: 'John', salary: 30000 },
{ id: 2, name: 'Jane', salary: 22000 },
{ id: 3, name: 'Alice', salary: 28000 },
{ id: 4, name: 'Bob', salary: 26000 }
];

// Find employee with salary greater than 25000


const employee = [Link](emp => [Link] > 25000);

if (employee) {
[Link](`Employee found: ${[Link]}, Salary:
${[Link]}`);
} else {
[Link]('No employee found with salary greater than 25000');
}

Create Angular application that print the name of students who got 85% using filter and map method.

import { Component, OnInit } from '@angular/core';

@Component({
selector: 'app-student-list',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class StudentListComponent implements OnInit {
students = [
{ name: 'John Doe', score: 90 },
{ name: 'Jane Smith', score: 80 },
{ name: 'Bob Brown', score: 85 },
{ name: 'Alice Johnson', score: 95 },
{ name: 'Charlie Lee', score: 70 }
];

studentsWith85Percent: string[] = [];

ngOnInit(): void {
// Filter the students who scored 85% or more, then map to get
their names.
this.studentsWith85Percent = [Link]
.filter(student => [Link] >= 85) // Filters students with
score 85% or more
.map(student => [Link]); // Maps to just the names
}
}
<div>
<h2>Students with 85% or more:</h2>
<ul>
<li *ngFor="let student of studentsWith85Percent">{{ student
}}</li>
</ul>
</div>
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './[Link]';
import { StudentListComponent } from './student-list/student-
[Link]';

@NgModule({
declarations: [
AppComponent,
StudentListComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Common questions

Powered by AI

The architectural patterns for managing component data in Angular include MVC, MVVM, and Service-oriented architecture. In MVC, the Model manages data logic, the View displays data, and the Controller processes input. MVVM extends MVC by using bindings to synchronize data between the Model and View automatically. Service-oriented architecture as in RxJS focuses on using services to handle shared data or logic centrally, which enhances modularity and maintainability by reducing direct component coupling. Each pattern provides different trade-offs in complexity and separation of concerns .

Declaring validation rules clearly in an Express.js route setup ensures robust validation of incoming data, which is crucial for API consistency and security. By explicitly defining validation rules for request data, applications prevent incorrect or harmful data from processing, reducing errors, and potential security vulnerabilities. Moreover, well-defined validation provides developers with a consistent understanding of the requirements for API consumption, promoting uniform implementation across clients and minimizing integration issues .

Express.js uses middleware functions for handling POST request validation by employing libraries like 'express-validator'. This approach is necessary to ensure incoming data meets certain criteria before processing, enhancing security, and preventing malformed data from being saved or causing runtime errors. In the example, fields like name, email, and age are validated for their types and presence, with appropriate error messages returned for any failures. This validation is crucial for maintaining the integrity of the data within the application .

In AngularJS, in-memory data is typically managed within the scope of the controller, often initialized directly within the controller logic. For example, the array of 'games' is directly defined in the AngularJS controller's scope . In Express.js, in-memory data is often stored in a variable at the application level, outside the specific request handlers but accessible to them, allowing multiple route handlers to interact with this data. This approach is used to maintain state across different endpoints, as seen with the 'products' or 'employees' arrays in Express.js applications .

AngularJS handles asynchronous operations using promises and $http service to manage HTTP requests, promoting a clean chaining of operations and error handling with .then and .catch methods. Node.js, on the other hand, utilizes asynchronous callbacks, promises, and async/await for managing asynchronous tasks, with broader scope due to its event-driven architecture. Commonalities include non-blocking execution and improved responsiveness, but Node.js provides finer-grained control over async flow. AngularJS focuses more on the view and data-binding contexts for managing async operations, while Node.js emphasizes server-side task concurrency and I/O operations .

AngularJS uses directives like ng-repeat to iterate over a collection and render a dynamic list. The ng-click directive allows triggering functions on events, such as button clicks. In the provided example, ng-repeat iterates over the 'games' array and renders the list of games when the 'Show Games' button is clicked. The ng-click directive binds this button click to a function within the controller, which changes the visibility of the list by setting isListVisible to true .

Filter and map methods are built-in array methods used to process and manipulate arrays. The filter method creates a new array with all elements that pass a test implemented by a function, effectively reducing the array to matching elements. The map method creates a new array populated with the results of calling a provided function on every element in the array. They are often used together to first filter down a collection to relevant elements, and then transform or extract specific properties from these filtered elements, which is efficient and expressive in functional programming paradigms .

The @Input decorator in Angular is crucial for passing data from a parent component to a child component. It marks a property in the child component as property binding enabled, allowing changes made in the parent component to be bound and reflected in the child component. In the given implementation, @Input() item: string = ''; declares that 'item' can receive its value from the parent component, and this enables modular design and component reusability .

The Angular Component Lifecycle supports dynamic and efficient updates through its structured stages of initialization and change detection. OnInit is a lifecycle hook used for pre-initialization of data-fetching logic, which runs once the component has fully initialized. This ensures data-binding is set up after component setup, avoiding unnecessary rendering operations. Consequently, frequent changes in input properties trigger change detection that updates the DOM only when necessary, optimizing application performance .

Middleware in Express.js serves to process and manage requests, responses, and decision-making through the lifecycle of a web application. It benefits the application by allowing centralized handling of request parsing (e.g., body-parser), validation logic (e.g., express-validator), and error management. Middleware can be layered to perform functions like authentication or logging, thereby decoupling and modularizing functionalities, leading to cleaner, maintainable, and more secure applications .

You might also like