MEAN Stack CRUD- Angular 13

MEAN Stack CRUD- Angular 13

In this blog, we will look into how to perform Angular 13 crud operation using MEAN stack technology. We will use Angular, Node.JS, Express.Js, Bootstrap, and MongoDB to build the Angular MEAN crud applications.

Meaning of MEAN stack:

Mongo DB: It’s a document NoSQL database. It is cross-platform and open source.

Express JS: It’s a Node JS framework and it is totally web-based framework. It is also used to build RESTful APIs.

Angular: It’s a front-end framework based on typescript. This framework is developed by Google.

Node JS: It is JavaScript run-time environment. It executes JavaScript code outside of a browser and it is available for Windows, Linux, and macOS.

We will use a few plugins like Node JS, MongoDB, Mongoose JS, Express JS, Angular cli, and Visual Studio Code to create the MEAN stack app.

Firstly we are going to set up Node JS and Angular CLI:

We have to download and install NodeJS app on our machine. Next, we need to install Angular CLI using ‘npm install @angular/cli -g’ command in the command prompt.

Let’s create an Angular application and install bootstrap using the following command:

Ng new AnsiByteCode-mean-stack-cru

npm install bootstrapd        

After creating an angular app and installing bootstrap we need to add style to angular.json file of our app. Move forward to generate components inside the app under the component folder. For that we have to execute the below command:

ng g c components/employee-creat

ng g c components/employee-edit

ng g c components/employee-liste        

These commands will create 3 components for us and they will automatically be registered in app.module.ts file in our app.

Next, we are preparing the Backend (Node JS):

We have to create a separate folder called ‘backend’ to write manageable code for the backend using the command ‘mkdir backend’. After creating the folder go inside it using command ‘cd backend’.

Now we are inside the backend folder, we have to create package.json sing below command (1). Package.json file has metadata of our app it’s also known as a manifest file in Node JS app. To install the node package manager we need to execute the below command (2). The second command includes a few other required packages with a node package manager.

npm init –

npm install --save body-parser cors express mongoose nodemony        

Next inside the backend folder create server.js file and register these files in package.json using the command ‘touch server.js’. Now backend > server.js add the below code into it

let express = require('express')

   path = require('path'),

   mongoose = require('mongoose'),

   cors = require('cors'),

   bodyParser = require('body-parser'),

   dbConfig = require('./database/db');

 

// Connecting with mongo db

mongoose.Promise = global.Promise;

mongoose.connect(dbConfig.db, {

   useNewUrlParser: true

}).then(() => {       console.log('Database sucessfully connected')   },

   error => { console.log('Database could not connected: ' + error)   }

)

 

// Setting up port with express js

const employeeRoute = require('../backend/routes/employee.route')

const app = express();

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({

   extended: false

}));

app.use(cors());

app.use(express.static(path.join(__dirname, 'dist/mean-stack-crud-app')));

app.use('/', express.static(path.join(__dirname, 'dist/mean-stack-crud-app')));

app.use('/api', employeeRoute)

 

// Create port

const port = process.env.PORT || 4000;

const server = app.listen(port, () => {  console.log('Connected to port ' + port)})

// Find 404 and hand over to error handler

app.use((req, res, next) => {   next(createError(404));});,        

Next, we are creating a Model folder inside the backend folder and creating Employee. Js file inside Model folder.

mkdir models && cd model

touch Employee.jss        

Inside Employee.js file we need to define the schema for employee schema like the below code

const mongoose = require('mongoose')

const Schema = mongoose.Schema;

 

// Define collection and schema

let Employee = new Schema({

   name: {

      type: String

   },

   email: {

      type: String

   },

   designation: {

      type: String

   },

   phoneNumber: {

      type: Number

   }

}, {

   collection: 'employees'

})

 

module.exports = mongoose.model('Employee', Employee);        

After defining the schemas, we are going to create RESTful APIs using express js routes, first, create a route in the Angular app and access the data of the employee table using RESTful APIs. We are using Mongoose.js to perform CRUD from the MongoDB database. Create file ‘employee.route.js’ inside the route folder using the below command.

touch employee.route.js        

After that, we added the below code into this file to create RESTful APIs using mongoose.js.

const express = require('express')

const app = express();

const employeeRoute = express.Router();

 

// Employee model

let Employee = require('../models/Employee');

// Add Employee

employeeRoute.route('/create').post((req, res, next) => {

  Employee.create(req.body, (error, data) => {

    if (error) {   return next(error)

    } else {  res.json(data)    }

  })

});

 

// Get All Employees

employeeRoute.route('/').get((req, res) => {

  Employee.find((error, data) => {

    if (error) {  return next(error)

    } else { res.json(data)    }

  })

})

 

// Get single employee

employeeRoute.route('/read/:id').get((req, res) => {

  Employee.findById(req.params.id, (error, data) => {

    if (error) { return next(error)

    } else { res.json(data)    }

  })

})

 

 

// Update employee

employeeRoute.route('/update/:id').put((req, res, next) => {

  Employee.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 employee

employeeRoute.route('/delete/:id').delete((req, res, next) => {

  Employee.findOneAndRemove(req.params.id, (error, data) => {

    if (error) {  return next(error);

    } else {       res.status(200).json({  msg: data  })

    }

  })

})

 

module.exports = employeeRoute;;        

We have done the setup of the backend for our MEAN stack application. To start backend, nodemon server we have to run below command.

cd backen

nodemon serverd        

To start mongoDB server just go to the backend folder and open a new terminal and use the command ‘mongod’.

We have done with our backend part of the MEAN stack crud app. Now we will look into the frontend section which contains routing, RESTful API, Services, and multiple components in type script code.

To navigate routes between components, we have to set up routing in our application.

 By default, angular provide “app.routing.module.ts” file if we have selected yes while CLL asked the question “Would you like to add Angular routing?” during creating a new application. It is also registered in “app.module.ts”.

We have to include the below code in app.routing.module.ts to enable the routing service.

import { NgModule } from '@angular/core'

import { Routes, RouterModule } from '@angular/router';

import { EmployeeCreateComponent } from './components/employee-create/employee-create.component';

import { EmployeeListComponent } from './components/employee-list/employee-list.component';

import { EmployeeEditComponent } from './components/employee-edit/employee-edit.component';

const routes: Routes = [

  { path: '', pathMatch: 'full', redirectTo: 'create-employee' },

  { path: 'create-employee', component: EmployeeCreateComponent },

  { path: 'edit-employee/:id', component: EmployeeEditComponent },

  { path: 'employees-list', component: EmployeeListComponent }  

];

@NgModule({

  imports: [RouterModule.forRoot(routes)],

  exports: [RouterModule]

})

export class AppRoutingModule { };        

Also, include the below code into app.component.ts to enable the routing service.

<h5 class="my-0 mr-md-auto font-weight-bold">Ansi ByteCode LLP - MEAN Stack CRUD</h5

  <nav class="my-2 my-md-0 mr-md-3 px-4">

    <a class="btn btn-outline-primary btn-default" routerLinkActive="active" routerLink="/employees- list">View Employees</a>

<a class="btn btn-outline-primary btn-default" routerLinkActive="active" routerLink="/create-employee">Add Employee</a>

  </nav>

<router-outlet></router-outlet>>        

Next, we need to create a service file to use RESTfull APIs. Before that, we need to import the HttpClientModule in app.module.ts file.

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

imports: [

    HttpClientModule

  ],;        

Create a model folder and inside it employee.ts file under src with the below command:

ng g cl model/Employee        

Add the below code into employee.ts file:

export class Employee 

   name: string;

   email: string;

   designation: string;

   phoneNumber: number;

}{        

Create angular service with the below code to manage Angular MEAN stack CRUD.

ng g s service/api        

Now reach to src > app > service > api.service.ts and add below code into that.

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) {}

  // Create

  createEmployee(data): Observable<any> {

    let url = `${this.baseUri}/create`;

    return this.http.post(url, data).pipe(catchError(this.errorMgmt));

  }

  // Get all employees

  getEmployees() {

    return this.http.get(`${this.baseUri}`);

  };

// Get employe

  getEmployee(id): Observable<any> {

    let url = `${this.baseUri}/read/${id}`;

    return this.http.get(url, {headers: this.headers}).pipe(

      map((res: Response) => {

        return res || {}

      }),

      catchError(this.errorMgmt)

    )

  }

  // Update employee

  updateEmployee(id, data): Observable<any> {

    let url = `${this.baseUri}/update/${id}`;

    return this.http.put(url, data, { headers: this.headers }).pipe(

      catchError(this.errorMgmt)

    )

  }

  // Delete employee

  deleteEmployee(id): Observable<any> {

    let url = `${this.baseUri}/delete/${id}`;

    return this.http.delete(url, { headers: this.headers }).pipe(

      catchError(this.errorMgmt)

    )

  }e        

Now we need to import this service into app.module.ts file and proceed further

import { ApiService } from './service/api.service'

@NgModule({

  providers: [ApiService]

});        

Next, using the reactive form we can register and update employees. We start with creating employees in employee-create.component.ts file.

onSubmit() 

    this.submitted = true;

    if (!this.employeeForm.valid) {

      return false;

    } else {

      this.apiService.createEmployee(this.employeeForm.value).subscribe(

        (res) => {

          console.log('Employee successfully created!')

          this.ngZone.run(() => this.router.navigateByUrl('/employees-list'))

        }, (error) => {

          console.log(error);

        });

    }

  }{        

This will call the creatEmployee API which we created previously and perform an action accordingly. We also have to set up the code for HTML to view the UI. Next, we have to call the API form to show and delete the list of employees below

   readEmployee()

    this.apiService.getEmployees().subscribe((data) => {

     this.Employee = data;

    })   

  }

  removeEmployee(employee, index) {

    if(window.confirm('Are you sure?')) {

        this.apiService.deleteEmployee(employee._id).subscribe((data) => {

          this.Employee.splice(index, 1);

        }

      )   

    }

  }{        

Moving further and call the last API called “Update” like below

updateEmployee() 

    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.updateEmployee(id, this.editForm.value)

          .subscribe(res => {

            this.router.navigateByUrl('/employees-list');

            console.log('Content updated successfully!')

          }, (error) => {

            console.log(error)

          })

      }

    }

  }        

Now we completed our setup from the frontend side now using just one command “ng serve” we can execute the app and serve the UI on post 4200.

The application looks like below

No alt text provided for this image
No alt text provided for this image

To view or add a comment, sign in

Others also viewed

Explore topics