In this article, we’ll learn to create basic CRUD application using Angular 5, Nodejs, Express and MongoDB NoSQL database.
Introduction
We will create a demo project using Angular CLI for front-end, Node.js and Express for middle-end, and MongoDB for the back-end. In this article, we start from the beginning.
Requirement
- Visual Studio Code or any IDM for development.
- Node.js - if you already installed node, then check with node –v command and also check the npm command.
- MongoDB - In this project, we are using MongoDB database; you can also use SQL or other database.
If you already installed Angular CLI, globally check the version with this command ng -v
Download links
- Node - https://nodejs.org/en/download/
- VS code - https://code.visualstudio.com/
- MongoDB https://www.mongodb.com/download-center
Let’s start and create demo application.
Step 1
Create a new folder with any name, let's say, AngularCRUD. After the folder is created, then press ctrl+shift Right click for opening the command window here.
Step 2
After the folder opens in the command prompt, run this command for Angular CLI to install in our folder.
npm install -g @angular/cli
Step 3
If installed successfully, then run this command for creating a new application. Let's again set the project name as AngularCRUD.
ng new projectname
Step 4
When the ng new command is created and installed successfully, change your directory
cd AngularCRUD.
Step 5
Now, we open our project in Visual Studio code with code command like this.
Now, we can see VSCode opened automatically.
Step 6 Now run your application by using this command -
ng serve - o
Here, -o stands for opening application in default browser.
Step 7
Now, let us install Express and Mongoose body parser using this command.
- npm install express --save
- npm install mongoose -- save
- npm install body-parser --save
Step 8
After installing the above three packages, create a new file, server.js.
- var express = require('express');
- var path = require("path");
- var bodyParser = require('body-parser');
- var mongo = require("mongoose");
-
- var db = mongo.connect("mongodb://localhost:27017/AngularCRUD", function(err, response){
- if(err){ console.log( err); }
- else{ console.log('Connected to ' + db, ' + ', response); }
- });
-
-
- var app = express()
- app.use(bodyParser());
- app.use(bodyParser.json({limit:'5mb'}));
- app.use(bodyParser.urlencoded({extended:true}));
-
-
- app.use(function (req, res, next) {
- res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
- res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
- res.setHeader('Access-Control-Allow-Credentials', true);
- next();
- });
-
- var Schema = mongo.Schema;
-
- var UsersSchema = new Schema({
- name: { type: String },
- address: { type: String },
- },{ versionKey: false });
-
-
- var model = mongo.model('users', UsersSchema, 'users');
-
- app.post("/api/SaveUser",function(req,res){
- var mod = new model(req.body);
- if(req.body.mode =="Save")
- {
- mod.save(function(err,data){
- if(err){
- res.send(err);
- }
- else{
- res.send({data:"Record has been Inserted..!!"});
- }
- });
- }
- else
- {
- model.findByIdAndUpdate(req.body.id, { name: req.body.name, address: req.body.address},
- function(err,data) {
- if (err) {
- res.send(err);
- }
- else{
- res.send({data:"Record has been Updated..!!"});
- }
- });
-
-
- }
- })
-
- app.post("/api/deleteUser",function(req,res){
- model.remove({ _id: req.body.id }, function(err) {
- if(err){
- res.send(err);
- }
- else{
- res.send({data:"Record has been Deleted..!!"});
- }
- });
- })
-
-
-
- app.get("/api/getUser",function(req,res){
- model.find({},function(err,data){
- if(err){
- res.send(err);
- }
- else{
- res.send(data);
- }
- });
- })
-
-
- app.listen(8080, function () {
-
- console.log('Example app listening on port 8080!')
- })
Step 9
Let us open the project folder in other command prompt and run the node server.js on port 8080.
Setp 10
Create a new Angular Service for common AJAX API calling. Use thie commond
ng g s common –spec=false
Step 11 Write the following code in common.service.ts for API.
- import { Injectable } from '@angular/core';
- import {Http,Response, Headers, RequestOptions } from '@angular/http';
-
- import { Observable } from 'rxjs/Observable';
- import 'rxjs/add/operator/map';
- import 'rxjs/add/operator/do';
-
- @Injectable()
- export class CommonService {
-
- constructor(private http: Http) { }
-
- saveUser(user){
- return this.http.post('http://localhost:8080/api/SaveUser/', user)
- .map((response: Response) =>response.json())
- }
-
- GetUser(){
- return this.http.get('http://localhost:8080/api/getUser/')
- .map((response: Response) => response.json())
- }
- deleteUser(id){
- return this.http.post('http://localhost:8080/api/deleteUser/',{'id': id})
- .map((response: Response) =>response.json())
- }
-
- }
Step 12
Now, write the View code in app.module.ts file.
- import { BrowserModule } from '@angular/platform-browser';
- import { NgModule } from '@angular/core';
-
- import { HttpModule } from '@angular/http';
- import { FormsModule } from '@angular/forms';
-
- import { AppComponent } from './app.component';
-
- import {CommonService} from './common.service';
-
-
- @NgModule({
- declarations: [
- AppComponent
- ],
- imports: [
- BrowserModule,HttpModule,FormsModule,
- ],
- providers: [CommonService],
- bootstrap: [AppComponent]
- })
- export class AppModule { }
Step 13
Code for app.component.html.
- <form #userForm="ngForm" (ngSubmit)="onSave(userForm.value)" novalidate>
- <p>Is "myForm" valid? {{userForm.valid}}</p>
- <table border='1'>
- <tr>
- <td>name</td>
- <td>
- <input name="id" type="hidden" [(ngModel)]="id" />
- <input name="name" type="text" required [(ngModel)]="name" />
-
- </td>
- </tr>
-
- <tr>
- <td>address</td>
- <td> <input name="address" required type="text" [(ngModel)]="address" /></td>
- </tr>
- <tr>
- <td colspan="2">
- <input type="submit" value="{{valbutton}}" />
- </td>
- </tr>
- </table>
- </form>
-
- <table border='1'>
-
- <tr>
- <td>Id</td>
- <td>Name</td>
- <td>Address</td>
- <td>Edit</td>
- <td>Delete</td>
- </tr>
- <tr *ngFor="let kk of Repdata;let ind = index">
-
- <td>{{ind + 1}}</td>
- <td>{{kk.name}}</td>
- <td>{{kk.address}}</td>
- <td><a (click)="edit(kk)" style="color:blueviolet">Edit</a></td>
- <td><a (click)="delete(kk._id)" style="color:blueviolet">Delete</a> </td>
- </tr>
- </table>
-
-
-
Step 14 Write this code in app.component.ts and remove the existing code from this file.
-
- import { Component, OnInit } from '@angular/core';
- import {FormGroup,FormControl,Validators,FormsModule, } from '@angular/forms';
- import {CommonService} from './common.service';
-
- import {Http,Response, Headers, RequestOptions } from '@angular/http';
-
- @Component({
- selector: 'app-root',
- templateUrl: './app.component.html',
- styleUrls: ['./app.component.css']
- })
- export class AppComponent {
-
-
- constructor(private newService :CommonService,) { }
- Repdata;
- valbutton ="Save";
-
-
- ngOnInit() {
- this.newService.GetUser().subscribe(data => this.Repdata = data)
- }
-
- onSave = function(user,isValid: boolean) {
- user.mode= this.valbutton;
- this.newService.saveUser(user)
- .subscribe(data => { alert(data.data);
-
- this.ngOnInit();
- }
- , error => this.errorMessage = error )
-
- }
- edit = function(kk) {
- this.id = kk._id;
- this.name= kk.name;
- this.address= kk.address;
- this.valbutton ="Update";
- }
-
- delete = function(id) {
- this.newService.deleteUser(id)
- .subscribe(data => { alert(data.data) ; this.ngOnInit();}, error => this.errorMessage = error )
- }
-
- }
We are almost done for performing select, insert, update, delete operation. Now, let us run two servers. The first one is Angular application with command ng server-o and the second one is to open node.js server.
We seen the output on borwser port 4200.
Summary
In this article, we learned how to create CRUD application with Angular 5 and node. I hope you enjoyed this article. If you have any query related to this code, please comment in the comments section.