Quick Contact


    MeanStack Building Single Page with Angular

    Angular is the second JavaScript framework in the MEAN stack, allowing for the creation of single-page apps using a clean Model View Controller (MVC) approach. We’ve now installed our modules, setup our application for database, express settings, and routes, and launched our server. Notice how we didn’t bring in any mongoose. It is not required at this time. It will be used in our model, which we shall outline shortly.

    You’ll need a local MongoDB database to make this to work, or you can use one of the fast one-off services like Modulus or Mongolab. Simply sign up for one of these services, create a database using your own credentials, and you’ll be able to retrieve the URL string to use in your own config file.

    After that, we’ll create a simple Mongoose model to store our Nerds in our database.

    As a front-end framework, AngularJS makes use of the following components.
    • Installs files and libraries with Bower.
    • For Angular application structure, controllers and services are used.
    • Creates various HTML pages
    • For AngularJS applications, the ngRoute module is used to handle routing and services.
    • Bootstrap is used to make an application more appealing.
    Getting Our Angular Application Started:-

    Let’s create a basic app using a Node.js backend and an AngularJS frontend. We’ll need the following for our Angular application:

    • Two distinct pages (Home, Student)
    • Each has its own angular controller.
    • When switching pages, there is no need to reload the page.
    Bower and Pulling in Components

    Certain files, like as bootstrap and angular, will be required for our programme. Bower will be tasked with retrieving those components.

    To begin, run the following command in your command prompt to install bower on your system.

    bower -g npm install

    This will set up bower on your system and make it available to everyone. Now, inside your root folder, place the files.bowerrc and bower.json. It is mean-demo in our situation. The following is a list of what’s in both files:

    bower.json – Like package.json, this file tells Bower which packages are required.

    Example:-
    
    	const express = require('express');
    	const app = express();
    	constStudentRoute = express.Router();
    
    	// Student model
    	let Student = require('../models/Student');
    
    
    	StudentRoute.route('/create').post((req, res, next) => {
    	Student.create(req.body, (error, data) => {
    	if (error) {
    	return next(error)
    	    } else {
    	StudentRoute.route('/').get((req, res) => {
    	Student.find((error, data) => {
    	if (error) {
    	return next(error)
    	    } else {
    	res.json(data)
    	    }
    	  })
    	})
    
    	// Get single Student
    	StudentRoute.route('/read/:id').get((req, res) => {
    	Student.findById(req.params.id, (error, data) => {
    	if (error) {
    	return next(error)
    	    } else {
    	res.json(data)
    	    }
    	  })
    	})
    
    
    	// Update Student
    	StudentRoute.route('/update/:id').put((req, res, next) => {
    	Student.findByIdAndUpdate(req.params.id, {
    	    $set: req.body
    	  }, (error, data) => {
    	if (error) {
    	return next(error);
    	console.log(error)
    	    } else {
    	res.json(data)
    	console.log('Data updated successfully')
    	    }
    	  })
    	})
    
    	// Delete Student
    	StudentRoute.route('/delete/:id').delete((req, res, next) => {
    	Student.findOneAndRemove(req.params.id, (error, data) => {
    	if (error) {
    	return next(error);
    	    } else {
    	res.status(200).json({
    	msg: data
    	      })
    	StudentRoute.route('/').get((req, res) => {
    	Student.find((error, data) => {
    	if (error) {
    	return next(error)
    	    } else {
    	res.json(data)
    	    }
    	  })
    	})
    
    	// Get single Student
    	StudentRoute.route('/read/:id').get((req, res) => {
    	Student.findById(req.params.id, (error, data) => {
    	if (error) {
    	return next(error)
    	    } else {
    	res.json(data)
    	    }
    	  })
    	})
    
    
    	// Update Student
    	StudentRoute.route('/update/:id').put((req, res, next) => {
    	Student.findByIdAndUpdate(req.params.id, {
    	    $set: req.body
    	  }, (error, data) => {
    	if (error) {
    	return next(error);
    	console.log(error)
    	    } else {
    	res.json(data)
    	console.log('Data updated successfully')
    	    }
    	  })
    	})
    
    	// Delete Student
    	StudentRoute.route('/delete/:id').delete((req, res, next) => {
    	Student.findOneAndRemove(req.params.id, (error, data) => {
    	if (error) {
    	return next(error);
    	    } else {
    	res.status(200).json({
    	msg: data
    	      })
    	StudentRoute.route('/').get((req, res) => {
    	Student.find((error, data) => {
    	if (error) {
    	return next(error)
    	    } else {
    	res.json(data)
    	    }
    	  })
    	})
    
    	// Get single Student
    	StudentRoute.route('/read/:id').get((req, res) => {
    	Student.findById(req.params.id, (error, data) => {
    	if (error) {
    	return next(error)
    	    } else {
    	res.json(data)
    	    }
    	  })
    	})
    
    
    	// Update Student
    	StudentRoute.route('/update/:id').put((req, res, next) => {
    	Student.findByIdAndUpdate(req.params.id, {
    	    $set: req.body
    	  }, (error, data) => {
    	if (error) {
    	return next(error);
    	console.log(error)
    	    } else {
    	res.json(data)
    	console.log('Data updated successfully')
    	    }
    	  })
    	})
    
    	// Delete Student
    	StudentRoute.route('/delete/:id').delete((req, res, next) => {
    	Student.findOneAndRemove(req.params.id, (error, data) => {
    	if (error) {
    	return next(error);
    	    } else {
    	res.status(200).json({
    	msg: data
    	      })
    	StudentRoute.route('/').get((req, res) => {
    	Student.find((error, data) => {
    	if (error) {
    	return next(error)
    	    } else {
    	res.json(data)
    	    }
    	  })
    	})
    
    	// Get single Student
    	StudentRoute.route('/read/:id').get((req, res) => {
    	Student.findById(req.params.id, (error, data) => {
    	if (error) {
    	return next(error)
    	    } else {
    	res.json(data)
    	    }
    	  })
    	})
    
    	StudentRoute.route('/update/:id').put((req, res, next) => {
    	Student.findByIdAndUpdate(req.params.id, {
    	    $set: req.body
    	  }, (error, data) => {
    	if (error) {
    	return next(error);
    	console.log(error)
    	    } else {
    	res.json(data)
    	console.log('Data updated successfully')
    	    }
    	  })
    	})
    
    	// Delete Student
    	StudentRoute.route('/delete/:id').delete((req, res, next) => {
    	Student.findOneAndRemove(req.params.id, (error, data) => {
    	if (error) {
    	return next(error);
    	    } else {
    	res.status(200).json({
    	msg: data
    	      })
    	res.json(data)
    	    }
    	  })
    	});
    
    	// Get All Students
    	StudentRoute.route('/').get((req, res) => {
    	Student.find((error, data) => {
    	if (error) {
    	return next(error)
    	    } else {
    	res.json(data)
    	    }
    	  })
    	})
    
    	// Get single Student
    	StudentRoute.route('/read/:id').get((req, res) => {
    	Student.findById(req.params.id, (error, data) => {
    	if (error) {
    	return next(error)
    	    } else {
    	res.json(data)
    	    }
    	  })
    	})
    
    	StudentRoute.route('/update/:id').put((req, res, next) => {
    	Student.findByIdAndUpdate(req.params.id, {
    	    $set: req.body
    	  }, (error, data) => {
    	if (error) {
    	return next(error);
    	console.log(error)
    	    } else {
    	res.json(data)
    	console.log('Data updated successfully')
    	    }
    	  })
    	})
    
    	// Delete Student
    	StudentRoute.route('/delete/:id').delete((req, res, next) => {
    	Student.findOneAndRemove(req.params.id, (error, data) => {
    	if (error) {
    	return next(error);
    	    } else {
    	res.status(200).json({
    	msg: data
    	      })
    	    }
    	  })
    	})
    	module.exports = StudentRoute;
    	$ bower install
    	
    Angular Routes
    
    	public/js/appRoutes.js :-
    
    	var express = require('express');
    	var app = express();                        
    	var mongoose = require('mongoose');                 
    	var port = process.env.PORT || 8080;                // set the port
    	var database = require('./config/database');            // load the database config
    	varmorgan = require('morgan');
    	varbodyParser = require('body-parser');
    	varmethodOverride = require('method-override');
    
    	mongoose.connect(database.localUrl);    // Connect to local MongoDB instance. A remoteUrl is also available (modulus.io)
    
    	app.use(express.static('./public'));        // set the static files location /public/img will be /img for users
    	app.use(morgan('dev')); // log every request to the console
    	app.use(bodyParser.urlencoded({'extended': 'true'})); // parse application/x-www-form-urlencoded
    	app.use(bodyParser.json()); // parse application/json
    	app.use(bodyParser.json({type: 'application/vnd.api+json'})); // parse application/vnd.api+json as json
    	app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request
    
    	angular.connect(database.localUrl);    // Connect to local MongoDB instance. A remoteUrl is also available (modulus.io)
    
    	app.use(express.static('./public'));       
    	app.use(morgan('dev')); // log every request to the console
    	app.use(bodyParser.urlencoded({'extended': 'true'})); // parse application/x-www-form-urlencoded
    	app.use(bodyParser.json()); // parse application/json
    	app.use(bodyParser.json({type: 'application/vnd.api+json'})); // parse application/vnd.api+json as json
    	app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request
    	mongoose.connect(database.localUrl);    // Connect to local MongoDB instance. A remoteUrl is also available (modulus.io)
    
    	app.use(express.static('./public'));        
    	app.use(morgan('dev')); // log every request to the console
    	app.use(bodyParser.urlencoded({'extended': 'true'})); // parse application/x-www-form-urlencoded
    	app.use(bodyParser.json()); // parse application/json
    	app.use(bodyParser.json({type: 'application/vnd.api+json'})); // parse application/vnd.api+json as json
    	app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request
    	mongoose.connect(database.localUrl);    // Connect to local MongoDB instance. A remoteUrl is also available (modulus.io)
    
    	app.use(express.static('./public'));        // set the static files location /public/img will be /img for users
    	app.use(morgan('dev')); // log every request to the console
    	app.use(bodyParser.urlencoded({'extended': 'true'})); // parse application/x-www-form-urlencoded
    	app.use(bodyParser.json()); // parse application/json
    	app.use(bodyParser.json({type: 'application/vnd.api+json'})); // parse application/vnd.api+json as json
    	app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request
    	require('./app/routes.js')(app);
    
    	    // listen (start app with node server.js) 
    	app.listen(port);
    	console.log("App listening on port " + port);
    	
    View File

    Angular employs the template file, which may be injected into the index.html file’s div ng-view>/div>. The ng-view directive provides a placeholder where, depending on the settings, a corresponding view (HTML or ng-template view) may be put. Visit this page for additional information about angular views.

    Routing is defined using Express app object methods that correspond to HTTP methods, such as app.get() for GET requests and app.post() for POST requests. See app.METHOD for a complete list. App.all() may be used to handle all HTTP methods, whereas app.use() can be used to provide middleware as the callback function (See Using middleware for details).

    When the application gets a request to the given route (endpoint) and HTTP method, these routing methods define a callback function (also known as “handler functions”). To put it another way, the application “listens” for requests that match the given route(s) and method(s) and responds when it finds one.

    Create smaller template files and inject them into the index.html file after you’ve finished routing. The following code snippet will be included in the index.html file.

    Code:-
    
    	< div class="row justify-content-center">
    	< div class="col-md-4 register-Candidates">
    	< !-- form card register -->
    	< div class="card card-outline-secondary">
    	< div class="card-header">
    	< h3 class="mb-0">Edit Candidates< /h3>
    	< /div>
    	< div class="card-body">
    	< form [formGroup]="editForm" (ngSubmit)="onSubmit()">
    
    	< div class="form-group">
    	< label for="inputName">Name< /label>
    	< input class="form-control" type="text" formControlName="name">
    	< div class="invalid-feedback" *ngIf="Apply &&myForm.name.errors?.required">
    	               Name is required.
    	< /div>
    	< /div>
    	< div class="form-group">
    	< label for="inputEmail3">Email< /label>
    	< input class="form-control" type="text" formControlName="email">
    	< !-- error -->
    	< div class="invalid-feedback" *ngIf="Apply &&myForm.email.errors?.required">
    	               Enter your email.
    	< /div>
    	< div class="invalid-feedback" *ngIf="Apply &&myForm.email.errors?.pattern">
    	               Enter valid email.
    	< /div>
    	< /div>
    
    	< div class="form-group">
    	< label for="inputPassword3">Designation< /label>
    	< select class="custom-select form-control" (change)="updateProfile($event.target.value)"
    	formControlName="designation">
    	< option value="">Choose...< /option>
    	< option *ngFor="let CandidatesProfile of CandidatesProfile" value="{{CandidatesProfile}}">{{CandidatesProfile}}
    	< /option>
    	< /select>
    	< !-- error -->
    	< div class="invalid-feedback" *ngIf="Apply &&myForm.designation.errors?.required">
    	               Choose designation.
    	< /div>
    	< /div>
    	< div class="container">
    	< !-- No data message -->
    	< p *ngIf="Candidates.length<= 0" class="no-data text-center">There is no Candidates added yet!< /p>
    
    	< !-- Candidates list -->
    	< table class="table table-bordered" *ngIf="Candidates.length> 0">
    	< thead class="table-success">
    	< tr>
    	< th scope="col">Candidates ID< /th>
    	< th scope="col">Name< /th>
    	< th scope="col">Email< /th>
    	< th scope="col">Designation< /th>
    	< th scope="col">Phone No< /th>
    	< th scope="col center">Update< /th>
    	< /tr>
    	< /thead>
    	< tbody>
    	< tr *ngFor="let Candidates of Candidates; let i = index">
    	< th scope="row">{{Candidates._id}}< /th>
    	< td>{{Candidates.name}}< /td>
    	< td>{{Candidates.email}}< /td>
    	< td>{{Candidates.designation}}< /td>
    	< td>{{Candidates.phoneNumber}}< /td>
    	< td class="text-center edit-block">
    	< span class="edit" [routerLink]="['/edit-Candidates/', Candidates._id]">
    	< button type="button" class="btnbtn-success btn-sm">Edit< /button>
    	< /span>
    	< span class="delete" (click)="removeCandidates(Candidates, i)">
    	< button type="button" class="btnbtn-danger btn-sm">Delete< /button>
    	< /span>
    	< /td>
    	< /tr>
    	< /tbody>
    	< /table>
    	< /div>
    	< div class="container">
    	< !-- No data message -->
    	< p *ngIf="Candidates.length<= 0" class="no-data text-center">There is no Candidates added yet!< /p>
    
    	< !-- Candidates list -->
    	< table class="table table-bordered" *ngIf="Candidates.length> 0">
    	< thead class="table-success">
    	< tr>
    	< th scope="col">Candidates ID< /th>
    	< th scope="col">Name< /th>
    	< th scope="col">Email< /th>
    	< th scope="col">Designation< /th>
    	< th scope="col">Phone No< /th>
    	< th scope="col center">Update< /th>
    	< /tr>
    	< /thead>
    	< tbody>
    	< tr *ngFor="let Candidates of Candidates; let i = index">
    	< th scope="row">{{Candidates._id}}< /th>
    	< td>{{Candidates.name}}< /td>
    	< td>{{Candidates.email}}< /td>
    	< td>{{Candidates.designation}}< /td>
    	< td>{{Candidates.phoneNumber}}< /td>
    	< td class="text-center edit-block">
    	< span class="edit" [routerLink]="['/edit-Candidates/', Candidates._id]">
    	< button type="button" class="btnbtn-success btn-sm">Edit< /button>
    	< /span>
    	< span class="delete" (click)="removeCandidates(Candidates, i)">
    	< button type="button" class="btnbtn-danger btn-sm">Delete< /button>
    	< /span>
    	< /td>
    	< /tr>
    	< /tbody>
    	< /table>
    	< /div>
    	< div class="container">
    	< !-- No data message -->
    	< p *ngIf="Candidates.length<= 0" class="no-data text-center">There is no Candidates added yet!< /p>
    
    	< !-- Candidates list -->
    	< table class="table table-bordered" *ngIf="Candidates.length> 0">
    	< thead class="table-success">
    	< tr>
    	< th scope="col">Candidates ID< /th>
    	< th scope="col">Name< /th>
    	< th scope="col">Email< /th>
    	< th scope="col">Designation< /th>
    	< th scope="col">Phone No< /th>
    	< th scope="col center">Update< /th>
    	< /tr>
    	< /thead>
    	< tbody>
    	< tr *ngFor="let Candidates of Candidates; let i = index">
    	< th scope="row">{{Candidates._id}}< /th>
    	< td>{{Candidates.name}}< /td>
    	< td>{{Candidates.email}}< /td>
    	< td>{{Candidates.designation}}< /td>
    	< td>{{Candidates.phoneNumber}}< /td>
    	< td class="text-center edit-block">
    	< span class="edit" [routerLink]="['/edit-Candidates/', Candidates._id]">
    	< button type="button" class="btnbtn-success btn-sm">Edit< /button>
    	< /span>
    	< span class="delete" (click)="removeCandidates(Candidates, i)">
    	< button type="button" class="btnbtn-danger btn-sm">Delete< /button>
    	< /span>
    	< /td>
    	< /tr>
    	< /tbody>
    	< /table>
    	< /div>
    	< div class="form-group">
    	< label for="inputVerify3">Mobile No< /label>
    	< input class="form-control" type="text" formControlName="phoneNumber">
    	< !-- error -->
    	< div class="invalid-feedback" *ngIf="Apply &&myForm.phoneNumber.errors?.required">
    	               Enter your phone number.
    	< /div>
    	< div class="invalid-feedback" *ngIf="Apply &&myForm.phoneNumber.errors?.pattern">
    	               Enter Numbers Only
    	< /div>
    	< /div>
    
    	< div class="form-group">
    	< button class="btnbtn-success btn-lgbtn-block" type="submit">Update< /button>
    	< /div>
    	< /form>
    	< /div>
    	< /div>< !-- form  -->
    	< /div>
    	< /div>
    	
    To edit employee data, we must first add the following code to the page.
    
    	students-edit.component.ts
    	import { Candidates } from './../../model/Candidates';
    	import { Component, OnInit } from '@angular/core';
    	import { ActivatedRoute, Router } from "@angular/router";
    	import { ApiService } from './../../service/api.service';
    	import { FormGroup, FormBuilder, Validators } from "@angular/forms";
    
    
    	@Component({
    	selector: 'app-Candidates-edit',
    	templateUrl: './Candidates-edit.component.html',
    	styleUrls: ['./Candidates-edit.component.css']
    	})
    
    	export class CandidatesEditComponent implements OnInit {
    	submitted = false;
    	editForm: FormGroup;
    	CandidatesData: Candidates[];
    	CandidatesProfile: any = ['Finance', 'BDM', 'HR', 'Sales', 'Admin']
    
    	constructor(
    	publicfb: FormBuilder,
    	privateactRoute: ActivatedRoute,
    	privateapiService: ApiService,
    	private router: Router
    	  ) {}
    
    	ngOnInit() {
    	this.updateCandidates();
    	let id = this.actRoute.snapshot.paramMap.get('id');
    	this.getCandidates(id);
    	this.editForm = this.fb.group({
    	name: ['', [Validators.required]],
    	email: ['', [Validators.required, Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$')]],
    	designation: ['', [Validators.required]],
    	private router: Router
    	  ) {}
    
    	ngOnInit() {
    	this.updateCandidates();
    	let id = this.actRoute.snapshot.paramMap.get('id');
    	this.getCandidates(id);
    	this.editForm = this.fb.group({
    	name: ['', [Validators.required]],
    	email: ['', [Validators.required, Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$')]],
    	designation: ['', [Validators.required]],
    	phoneNumber: ['', [Validators.required, Validators.pattern('^[0-9]+$')]]
    	    })
    	  }
    
    	  // Choose options with select-dropdown
    	updateProfile(e) {
    	this.editForm.get('designation').setValue(e, {
    	onlySelf: true
    	    })
    	  }
    
    	  // Getter to access form control
    	getmyForm() {
    	returnthis.editForm.controls;
    	  }
    
    	getCandidates(id) {
    	this.apiService.getCandidates(id).subscribe(data => {
    	this.editForm.setValue({
    	name: data['name'],
    	email: data['email'],
    	designation: data['designation'],
    	phoneNumber: data['phoneNumber'],
    	      });
    	    });
    	  }
    
    	updateCandidates() {
    	this.editForm = this.fb.group({
    	name: ['', [Validators.required]],
    	email: ['', [Validators.required, Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$')]],
    	designation: ['', [Validators.required]],
    	phoneNumber: ['', [Validators.required, Validators.pattern('^[0-9]+$')]]
    	    })
    	  }
    
    	onSubmit() {
    	this.submitted = true;
    	if (!this.editForm.valid) {
    	return false;
    	    } else {
    	if (window.confirm('Are you sure?')) {
    	let id = this.actRoute.snapshot.paramMap.get('id');
    	this.apiService.updateCandidates(id, this.editForm.value)
    	          .subscribe(res => {
    	private router: Router
    	  ) {}
    
    	ngOnInit() {
    	this.updateCandidates();
    	let id = this.actRoute.snapshot.paramMap.get('id');
    	this.getCandidates(id);
    	this.editForm = this.fb.group({
    	name: ['', [Validators.required]],
    	email: ['', [Validators.required, Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$')]],
    	designation: ['', [Validators.required]],
    	phoneNumber: ['', [Validators.required, Validators.pattern('^[0-9]+$')]]
    	    })
    	  }
    
    	  // Choose options with select-dropdown
    	updateProfile(e) {
    	this.editForm.get('designation').setValue(e, {
    	onlySelf: true
    	    })
    	  }
    
    	  // Getter to access form control
    	getmyForm() {
    	returnthis.editForm.controls;
    	  }
    
    	getCandidates(id) {
    	this.apiService.getCandidates(id).subscribe(data => {
    	this.editForm.setValue({
    	name: data['name'],
    	email: data['email'],
    	designation: data['designation'],
    	phoneNumber: data['phoneNumber'],
    	      });
    	    });
    	  }
    
    	updateCandidates() {
    	this.editForm = this.fb.group({
    	name: ['', [Validators.required]],
    	email: ['', [Validators.required, Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$')]],
    	designation: ['', [Validators.required]],
    	phoneNumber: ['', [Validators.required, Validators.pattern('^[0-9]+$')]]
    	    })
    	  }
    
    	onSubmit() {
    	this.submitted = true;
    	if (!this.editForm.valid) {
    	return false;
    	    } else {
    	if (window.confirm('Are you sure?')) {
    	let id = this.actRoute.snapshot.paramMap.get('id');
    	this.apiService.updateCandidates(id, this.editForm.value)
    	          .subscribe(res => {
    	private router: Router
    	  ) {}
    
    	ngOnInit() {
    	this.updateCandidates();
    	let id = this.actRoute.snapshot.paramMap.get('id');
    	this.getCandidates(id);
    	this.editForm = this.fb.group({
    	name: ['', [Validators.required]],
    	email: ['', [Validators.required, Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$')]],
    	designation: ['', [Validators.required]],
    	phoneNumber: ['', [Validators.required, Validators.pattern('^[0-9]+$')]]
    	    })
    	  }
    
    	  // Choose options with select-dropdown
    	updateProfile(e) {
    	this.editForm.get('designation').setValue(e, {
    	onlySelf: true
    	    })
    	  }
    
    	  // Getter to access form control
    	getmyForm() {
    	returnthis.editForm.controls;
    	  }
    
    	getCandidates(id) {
    	this.apiService.getCandidates(id).subscribe(data => {
    	this.editForm.setValue({
    	name: data['name'],
    	email: data['email'],
    	designation: data['designation'],
    	phoneNumber: data['phoneNumber'],
    	      });
    	    });
    	  }
    
    	updateCandidates() {
    	this.editForm = this.fb.group({
    	name: ['', [Validators.required]],
    	email: ['', [Validators.required, Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$')]],
    	designation: ['', [Validators.required]],
    	phoneNumber: ['', [Validators.required, Validators.pattern('^[0-9]+$')]]
    	    })
    	  }
    
    	onSubmit() {
    	this.submitted = true;
    	if (!this.editForm.valid) {
    	return false;
    	    } else {
    	if (window.confirm('Are you sure?')) {
    	let id = this.actRoute.snapshot.paramMap.get('id');
    	this.apiService.updateCandidates(id, this.editForm.value)
    	          .subscribe(res => {
    	phoneNumber: ['', [Validators.required, Validators.pattern('^[0-9]+$')]]
    	    })
    	  }
    
    	  // Choose options with select-dropdown
    	updateProfile(e) {
    	this.editForm.get('designation').setValue(e, {
    	onlySelf: true
    	    })
    	  }
    
    	  // Getter to access form control
    	getmyForm() {
    	returnthis.editForm.controls;
    	  }
    
    	getCandidates(id) {
    	this.apiService.getCandidates(id).subscribe(data => {
    	this.editForm.setValue({
    	name: data['name'],
    	email: data['email'],
    	designation: data['designation'],
    	phoneNumber: data['phoneNumber'],
    	      });
    	    });
    	  }
    
    	updateCandidates() {
    	this.editForm = this.fb.group({
    	name: ['', [Validators.required]],
    	email: ['', [Validators.required, Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$')]],
    	designation: ['', [Validators.required]],
    	phoneNumber: ['', [Validators.required, Validators.pattern('^[0-9]+$')]]
    	    })
    	  }
    
    	onSubmit() {
    	this.submitted = true;
    	if (!this.editForm.valid) {
    	return false;
    	    } else {
    	if (window.confirm('Are you sure?')) {
    	let id = this.actRoute.snapshot.paramMap.get('id');
    	this.apiService.updateCandidates(id, this.editForm.value)
    	          .subscribe(res => {
    	this.router.navigateByUrl('/Candidatess-list');
    	console.log('Content updated successfully!')
    	          }, (error) => {
    	console.log(error)
    	          })
    	      }
    	    }
    	  }
    	}
    	

    To manage a request, you may specify several callback methods that act as middleware. The only difference is that these callbacks may use next(‘route’) to skip the remaining route callbacks. This method can be used to put pre-conditions on a route, then pass control to future routes if the present route isn’t necessary.

    As illustrated in the examples below, route handlers can be in the form of a function, an array of functions, or a mix of both.

    A route can be handled by a single callback function. Consider the following scenario:

    api.service.ts

    Code:-
    
    	import { Injectable } from '@angular/core';
    	import { Observable, throwError } from 'rxjs';
    	import { catchError, map } from 'rxjs/operators';
    	import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
    
    	@Injectable({
    	providedIn: 'root'
    	})
    
    	export class ApiService {
    
    	baseUri:string = 'http://localhost:4000/api';
    	headers = new HttpHeaders().set('Content-Type', 'application/json');
    
    	constructor(private http: HttpClient) { }
    
    	createCandidates(data): Observable< any> {
    	leturl = `${this.baseUri}/create`;
    	returnthis.http.post(url, data)
    	      .pipe(
    	catchError(this.errorMgmt)
    	      )
    	  }
    
    	getCandidatess() {
    	returnthis.http.get(`${this.baseUri}`);
    	  }
    
    	getCandidates(id): Observable< any> {
    	leturl = `${this.baseUri}/read/${id}`;
    	returnthis.http.get(url, {headers: this.headers}).pipe(
    	map((res: Response) => {
    	return res || {}
    	      }),
    	catchError(this.errorMgmt)
    	    )
    	  }
    
    	updateCandidates(id, data): Observable< any> {
    	leturl = `${this.baseUri}/update/${id}`;
    	returnthis.http.put(url, data, { headers: this.headers }).pipe(
    	catchError(this.errorMgmt)
    	    )
    	  }
    
    	deleteCandidates(id): Observable< any> {
    	leturl = `${this.baseUri}/delete/${id}`;
    	returnthis.http.delete(url, { headers: this.headers }).pipe(
    	catchError(this.errorMgmt)
    	    )
    	  }
    	baseUri:string = 'http://localhost:4000/api';
    	headers = new HttpHeaders().set('Content-Type', 'application/json');
    
    	constructor(private http: HttpClient) { }
    
    	createCandidates(data): Observable< any> {
    	leturl = `${this.baseUri}/create`;
    	returnthis.http.post(url, data)
    	      .pipe(
    	catchError(this.errorMgmt)
    	      )
    	  }
    
    	getCandidatess() {
    	returnthis.http.get(`${this.baseUri}`);
    	  }
    
    	getCandidates(id): Observable< any> {
    	leturl = `${this.baseUri}/read/${id}`;
    	returnthis.http.get(url, {headers: this.headers}).pipe(
    	map((res: Response) => {
    	return res || {}
    	baseUri:string = 'http://localhost:4000/api';
    	headers = new HttpHeaders().set('Content-Type', 'application/json');
    
    	constructor(private http: HttpClient) { }
    	< head>
    	  ...
    	< scriptsrc="lib/angular/angular.js">< /script>
    	< scriptsrc="lib/angular-route/angular-route.js">< /script>
    	< scriptsrc="app.module.js">< /script>
    	< scriptsrc="app.config.js">< /script>
    	  ...
    	< scriptsrc="phone-detail/phone-detail.module.js">< /script>
    	< scriptsrc="phone-detail/phone-detail.component.js">< /script>
    	< /head>
    	< body>< script src="lib/angular/angular.js">< /script>
    	< scriptsrc="lib/angular-route/angular-route.js">< /script>
    	< scriptsrc="app.module.js">< /script>
    	< scriptsrc="app.config.js">< /script>
    	  ...
    	< scriptsrc="phone-detail/phone-detail.module.js">< /script>
    	< scriptsrc="phone-detail/phone-detail.component.js">< /script>
    	< /head>
    	< body>< script src="lib/angular/angular.js">< /script>
    	< scriptsrc="lib/angular-route/angular-route.js">< /script>
    	< scriptsrc="app.module.js">< /script>
    	< scriptsrc="app.config.js">< /script>
    	  ...
    	< scriptsrc="phone-detail/phone-detail.module.js">< /script>
    	< scriptsrc="phone-detail/phone-detail.component.js">< /script>
    	< /head>
    	< body>
    
    	< divng-view>< /div>
    
    	< /body>
    	createCandidates(data): Observable< any> {
    	leturl = `${this.baseUri}/create`;
    	returnthis.http.post(url, data)
    	      .pipe(
    	catchError(this.errorMgmt)
    	      )
    	  }
    
    	getCandidatess() {
    	returnthis.http.get(`${this.baseUri}`);
    	  }
    
    	getCandidates(id): Observable< any> {
    	leturl = `${this.baseUri}/read/${id}`;
    	returnthis.http.get(url, {headers: this.headers}).pipe(
    	map((res: Response) => {
    	baseUri:string = 'http://localhost:4000/api';
    	headers = new HttpHeaders().set('Content-Type', 'application/json');
    
    	constructor(private http: HttpClient) { }
    
    	createCandidates(data): Observable< any> {
    	leturl = `${this.baseUri}/create`;
    	returnthis.http.post(url, data)
    	      .pipe(
    	catchError(this.errorMgmt)
    	      )
    	  }
    
    	getCandidatess() {
    	returnthis.http.get(`${this.baseUri}`);
    	  }
    
    	getCandidates(id): Observable< any> {
    	leturl = `${this.baseUri}/read/${id}`;
    	returnthis.http.get(url, {headers: this.headers}).pipe(
    	map((res: Response) => {
    	return res || {}
    	return res || {}
    	errorMgmt(error: HttpErrorResponse) {
    	leterrorMessage = '';
    	if (error.errorinstanceofErrorEvent) {
    	errorMessage = error.error.message;
    	    } else {
    
    	errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
    	    }
    	console.log(errorMessage);
    	returnthrowError(errorMessage);
    	  }
    	}
    	
    Running Application

    This link will take you to the source code for this program. Download the zip file and unzip it on your computer. Open the terminal and run the below command to install npm module dependencies.

    $ cd mean-demo

    $ npm install

    When you click on the Students link, you’ll get the screen below.

    Copyright 1999- Ducat Creative, All rights reserved.