0% found this document useful (0 votes)
24 views

AngularProjectSolution 1

The document outlines the steps to build a basic CRUD application in Angular and Node.js/Express to manage employee data. It generates Angular components, sets up routing, creates Mongoose models and Express routes for CRUD operations, and includes a basic service for consuming the API.

Uploaded by

D46-Ramya M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

AngularProjectSolution 1

The document outlines the steps to build a basic CRUD application in Angular and Node.js/Express to manage employee data. It generates Angular components, sets up routing, creates Mongoose models and Express routes for CRUD operations, and includes a basic service for consuming the API.

Uploaded by

D46-Ramya M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

ng g c components/add-employee

ng g c components/employee-detail
ng g c components/employee-list

The interface must have the following pages:


-
 View all employees
 Add new employees
 Update existing employees
 Delete employees

app-routing.module.ts file.

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


import { Routes, RouterModule } from '@angular/router';
import { EmployeesListComponent } from './components/books-list/employees-
list.component';
import { AddemployeeComponent } from './components/add-book/add-
employee.component';
import { employeeDetailComponent } from './components/book-detail/employee-
detail.component';
const routes: Routes = [
{ path: '', pathMatch: 'full', redirectTo: 'add-employee' },
{ path: 'employees-list', component: EmployeesListComponent },
{ path: 'add-employee', component: AddemployeeComponent },
{ path: 'edit-employee/:id', component: employeeDetailComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AddemployeeComponent } from './components/add-book/add-
employee.component';
import { EmployeeDetailComponent } from './components/book-detail/employee-
detail.component';
import { employeesListComponent } from './components/books-list/employees-
list.component';
@NgModule({
declarations: [
AppComponent,
AddemployeeComponent,
EmployeeDetailComponent,
employeesListComponent,
],
imports: [
BrowserModule,
HttpClientModule,
FormsModule,
ReactiveFormsModule,
AppRoutingModule,
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}

Employee.js file
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Employee = new Schema({
name: {
type: String
},
position: {
type: String
},
level: {
type: String
}
}, {
collection: 'employees'
})
module.exports = mongoose.model('Employee', Employee)

employee.routes.js
const express = require("express");
const app = express();
const employeeRoute = express.Router();
let Employee = require("../model/Employee");
// CREATE
employeeRoute.route("/add-employee").post(async (req, res, next) => {
await Employee.create(req.body)
.then((result) => {
res.json({
data: result,
message: "Data successfully added!",
status: 200,
});
})
.catch((err) => {
return next(err);
});
});
// GET ALL
employeeRoute.route("/").get(async (req, res, next) => {
await Book.find()
.then((result) => {
res.json({
data: result,
message: "All items successfully fetched.",
status: 200,
});
})
.catch((err) => {
return next(err);
});
});
// GET SINGLE BY ID
employeeRoute.route("/read-employee/:id").get(async (req, res, next) => {
await Employee.findById(req.params.id)
.then((result) => {
res.json({
data: result,
message: "Data successfully fetched.",
status: 200,
});
})
.catch((err) => {
return next(err);
});
});
// UPDATE
employeeRoute.route("/update-employee/:id").put(async (req, res, next) => {
await Book.findByIdAndUpdate(req.params.id, {
$set: req.body,
})
.then((result) => {
res.json({
data: result,
msg: "Data successfully updated.",
});
})
.catch((err) => {
console.log(err);
});
});
// DELETE
employeeRoute.route("/delete-employee/:id").delete(async (req, res, next) => {
await Employee.findByIdAndRemove(req.params.id)
.then(() => {
res.json({
msg: "Data successfully updated.",
});
})
.catch((err) => {
console.log(err);
});
});
module.exports = bookRoute;

Create and add the below code in index.js file.

const express = require("express");


const path = require("path");
const mongoose = require("mongoose");
const cors = require("cors");
const bodyParser = require("body-parser");
mongoose
.connect("mongodb://127.0.0.1:27017/test")
.then((x) => {
console.log(
`Connected to Mongo! Database name: "${x.connections[0].name}"`
);
})
.catch((err) => {
console.error("Error connecting to mongo", err.reason);
});
const employeeRoute = require("./routes/employee.routes");
const app = express();
app.use(bodyParser.json());
app.use(
bodyParser.urlencoded({
extended: false,
})
);
app.use(cors());
// Static directory path
app.use(
express.static(path.join(__dirname, "dist/angular-mean-crud-tutorial"))
);
// API root
app.use("/api", bookRoute);
// PORT
const port = process.env.PORT || 8000;
app.listen(port, () => {
console.log("Listening on port " + port);
});
// 404 Handler
app.use((req, res, next) => {
next(createError(404));

});
// Base Route
app.get("/", (req, res) => {
res.send("invaild endpoint");
});
app.get("*", (req, res) => {
res.sendFile(
path.join(__dirname, "dist/angular-mean-crud-tutorial/index.html")
);
});
// error handler
app.use(function (err, req, res, next) {
console.error(err.message);
if (!err.statusCode) err.statusCode = 500;
res.status(err.statusCode).send(err.message);
});

The endpoints we created and you can use these to handle the CRUD operations
with Angular application:
Methods Endpoints

GET /api

POST /add-employee

GET /read-employee/id

PUT /update-employee/id

DELETE /delete-employee/id

Then, add the below code in app/service/Employee.ts file.

export class Employee {


_id!: String;
name!: String;
position!: String;
level!: String;
}

crud.service.ts
import { Injectable } from '@angular/core';
import { Employee } from './Employee';
import { catchError, map } from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';
import {
HttpClient,
HttpHeaders,
HttpErrorResponse,
} from '@angular/common/http';
@Injectable({
providedIn: 'root',
})
export class CrudService {
// Node/Express API
REST_API: string = 'http://localhost:8000/api';
// Http Header
httpHeaders = new HttpHeaders().set('Content-Type', 'application/json');
constructor(private httpClient: HttpClient) {}
// Add
AddEmployee(data: Employee): Observable<any> {
let API_URL = `${this.REST_API}/add-book`;
return this.httpClient
.post(API_URL, data)
.pipe(catchError(this.handleError));
}
// Get all objects
GetEmployees() {
return this.httpClient.get(`${this.REST_API}`);
}
// Get single object
GetEmployee(id: any): Observable<any> {
let API_URL = `${this.REST_API}/read-book/${id}`;
return this.httpClient.get(API_URL, { headers: this.httpHeaders }).pipe(
map((res: any) => {
return res || {};
}),
catchError(this.handleError)
);
}
// Update
updateEmployee(id: any, data: any): Observable<any> {
let API_URL = `${this.REST_API}/update-employee/${id}`;
return this.httpClient
.put(API_URL, data, { headers: this.httpHeaders })
.pipe(catchError(this.handleError));
}
// Delete
deleteEmployee(id: any): Observable<any> {
let API_URL = `${this.REST_API}/delete-employee/${id}`;
return this.httpClient
.delete(API_URL, { headers: this.httpHeaders })
.pipe(catchError(this.handleError));
}
// Error
handleError(error: HttpErrorResponse) {
let errorMessage = '';
if (error.error instanceof ErrorEvent) {
// Handle client error
errorMessage = error.error.message;
} else {
// Handle server error
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
console.log(errorMessage);
return throwError(() => {
errorMessage;
});
}
}

app.component.html file
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand">Angular Mean Stack 16 CRUD App Example</a>
<div id="navbarNav" class="collapse navbar-collapse">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" routerLinkActive="active" routerLink="/employees-list"
>Show Books</a
>
</li>
<li class="nav-item">
<a class="nav-link" routerLinkActive="active" routerLink="/add-employees"
>Add Books</a
>
</li>
</ul>
</div>
</nav>
<router-outlet></router-outlet>

add-employee.component.ts file
import { Component, OnInit, NgZone } from '@angular/core';
import { Router } from '@angular/router';
import { CrudService } from '../../service/crud.service';
import { FormGroup, FormBuilder } from '@angular/forms';
@Component({
selector: 'app-add-employee',
templateUrl: './add-employee.component.html',
styleUrls: ['./add-employee.component.scss'],
})
export class AddEmployeeComponent implements OnInit {
bookForm: FormGroup;
constructor(
public formBuilder: FormBuilder,
private router: Router,
private ngZone: NgZone,
private crudService: CrudService
){
this.employeeForm = this.formBuilder.group({
name: [''],
price: [''],
description: [''],
});
}
ngOnInit() {}
onSubmit(): any {
this.crudService.AddEmployee(this.employeeForm.value).subscribe(
(res: any) => {
console.log('Data added successfully!' + res);
this.ngZone.run(() => this.router.navigateByUrl('/books-list'));
},
(err: any) => {
console.log(err);
}
);
}
}

add-employee.component.html file:

<div class="row justify-content-center mt-5">


<div class="col-md-4">
<form [formGroup]="bookForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label>Name</label>
<input
class="form-control"
type="text"
formControlName="name"
required
/>
</div>
<div class="form-group">
<label>Position</label>
<input
class="form-control"
type="text"
formControlName="position"
required
/>
</div>
<div class="form-group">
<select id=”level”>
<option value=”Junior”> Junior<option>
<option value=”Mid”> Mid<option>
<option value=”Senior”> Senior<option>
</select>
<input class="form-control"
type="option"
formControlName="level"
required
/>
</div>
<div class="form-group">
<button class="btn btn-primary btn-block" type="submit">
Add Book
</button>
</div>
</form>
</div>
</div>

employees-list.component.ts file:

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


import { CrudService } from './../../service/crud.service';
@Component({
selector: 'app-employees-list',
templateUrl: './employees-list.component.html',
styleUrls: ['./employees-list.component.scss'],
})
export class EmployeesListComponent implements OnInit {
Employees: any = [];
constructor(private crudService: CrudService) {
this.crudService.GetEmployees().subscribe((data: any) => {
this.Employees = data.data;
});
}
ngOnInit() {}
delete(id: any, i: any) {
if (window.confirm('Do you want to go ahead?')) {
this.crudService.deleteEmployees(id).subscribe((data: any) => {
this.Employees.splice(i, 1);
});
}
}
}
Employees-list.component.html file:

<div class="container">
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-
center pt-3 pb-2 mb-3 border-bottom">
<h2 class="h2">Employeess List</h2>
</div>
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th scope="col">Id</th>
<th scope="col">Name</th>
<th scope="col">Position</th>
<th scope="col">Level</th>
<th class="text-center" scope="col">Action</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let book of Books; let i = index">
<th scope="row">{{book._id}}</th>
<td>{{employee.name}}</td>
<td>{{employee.position}}</td>
<td>{{employee.level}}</td>
<td class="text-center">
<button class="btn btn-sm btn-primary"
routerLink="/edit-employee/{{employee._id}}">Edit</button>
<button class="btn btn-sm btn-danger" (click)="delete(employee._id,
i)">Delete</button>
</tr>
</tbody>
</table>
</div>
</div>

Add the code in employee-detail.component.ts file:


import { Component, OnInit, NgZone } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { CrudService } from './../../service/crud.service';
import { FormGroup, FormBuilder } from "@angular/forms";
@Component({
selector: 'app-employee-detail',
templateUrl: './employee-detail.component.html',
styleUrls: ['./employee-detail.component.scss']
})
export class EmployeeDetailComponent implements OnInit {
getId: any;
updateForm: FormGroup;

constructor(
public formBuilder: FormBuilder,
private router: Router,
private ngZone: NgZone,
private activatedRoute: ActivatedRoute,
private crudService: CrudService
){
this.getId = this.activatedRoute.snapshot.paramMap.get('id');
this.crudService.GetEmployee(this.getId).subscribe((data: any) => {
this.updateForm.setValue({
name: data.data.name,
position: data.data.position,
Level: data.data.level
});
});
this.updateForm = this.formBuilder.group({
name: [''],
position: [''],
level: ['']
})
}
ngOnInit() { }
onUpdate(): any {
this.crudService.updateEmployee(this.getId, this.updateForm.value)
.subscribe(() => {
console.log('Data updated successfully!')
this.ngZone.run(() => this.router.navigateByUrl('/books-list'))
}, (err) => {
console.log(err);
});
}
}

employee-detail.component.html file:

<div class="row justify-content-center mt-5">


<div class="col-md-4">
<form [formGroup]="updateForm" (ngSubmit)="onUpdate()">
<div class="form-group">
<label>Name</label>
<input class="form-control" type="text" formControlName="name" required>
</div>
<div class="form-group">
<label>Position</label>
<input class="form-control" type="text" formControlName="price" required>
</div>
<div class="form-group">
<label>level</label>
<input class="form-control" type="text" formControlName="level" required>
</div>
<div class="form-group">
<button class="btn btn-primary btn-block" type="submit">Update</button>
</div>
</form>
</div>
</div>

For authentication in Employee Management Application 20M


Demo.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-demo',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
isAuthenticated!: boolean;
submitted = false;
userName!: string;
onSubmit(name: string, password: string) {
this.submitted = true;
this.userName = name;
if (name === 'admin' && password === 'admin') {
this.isAuthenticated = true;
} else {
this.isAuthenticated = false;
}
}
}

Demo.component.html
<div *ngIf="!submitted">
<form>
<label>User Name</label>
<input type="text" #username /><br /><br />
<label for="password">Password</label>
<input type="password" name="password" #password /><br />
</form>
<button (click)="onSubmit(username.value, password.value)">Login</button>
</div>
<div *ngIf="submitted">
<div *ngIf="isAuthenticated; else failureMsg">
<h4>goto(‘employees-list’)</h4>
</div>
<ng-template #failureMsg>
<h4>Invalid Login !!! Please try again...</h4>
</ng-template>
<button type="button" (click)="submitted = false">Back</button>
</div>

You might also like