Topic: Node.js

Send Email via SMTP Server in Node.js using Nodemailer npm 0

Send Email via SMTP Server in Node.js using Nodemailer npm

Send Email via SMTP Server in Node.js using Nodemailer npm

In this Post We Will Explain About is Send Email via SMTP Server in Node.js using Nodemailer npm With Example and Demo.Welcome on Pakainfo.com – Examples, The best For Learn web development Tutorials,Demo with Example! Hi Dear Friends here u can know to How To send emails using Node.js Example

In this post we will show you Best way to implement Node.js with Nodemailer npm, hear for Emailing in Node.js with Nodemailer with Download .we will give you demo,Source Code and examples for implement Step By Step Good Luck!.

In this Node.js POST, We will say you how to send simple email in npm Node.js using Nodemailer create module.
And then This makes it simple easy to send simple emails step by step from node web-application.
After that, You can best way to installed the Nodejs Nodemailer module using some npm command with Node.js
Now, Nodejs Nodemailer is know to licensed under Like as a MIT license.
Then, The most IMP Things is it all the support unicode, that means example you can use any some characters including like as a emoji.
Here, You can step by step send simple Row text as well DOM HTML data content.
After that, You can data embed some images, media in HTML, and also can put some attachments to send messages.
Nodejs Nodemailer more support different types of the transport methods Like as a- SMTP method, method of Sendmail as well as Amazon SES method.
In this Nodejs Nodemailer example, We are sharing simple source code to step by step send email in node web-application using Nodemailer module.

Step 2 : Installation

First step to simple Run following simple command cmd to install step by step Nodejs Nodemailer : Nodejs Installation

npm install nodemailer --save

Step 2 : Require Nodemailer module

Require the Nodemailer module in your js file :

var nodemailer = require('nodemailer');

Step 3 : sendMail function

function sendMail(to,subject,message) 
{
   var configDataSMTP = {
      service: 'Gmail',
      auth: {
          user: '[email protected]',
          pass: 'PUT_YOUR_PASS'
      }
   };
   var transporter = nodemailer.createTransport(configDataSMTP);
   var realTimeNodeMsgSend = {
      from: '"Sender(Live24u) Name" ', //Live24u sender address
      to: to, //Live24u list of receivers
      subject: subject, //Live24u Subject line
      text: 'Welcome to Live24u ?', //Live24u plaintext body
      html: message //Live24u html body
   };
   
   transporter.sendMail(realTimeNodeMsgSend, function(error, info){
      if(error)
      {
		//display error
         return console.log(error);
      }
      else
      {
	  //display response
         return console.log(info.response);
      }      
   }); 
}
var message = '<p>Live24u is the most popular Programming & Web Development blog. Our mission is to provide the best online resources on programming and web development. We deliver the useful and best tutorials for web professionals — developers, programmers, freelancers and site owners. Any visitors of this site are free to browse our tutorials, live demos and download scripts.</p>';
sendMail('[email protected]','Welcome to Pakainfo.com',message);

After that you can simple last step to use above all the npm function in your simple node web-application to successfully send email using best way to Nodemailer.

You are Most welcome in my youtube Channel Please subscribe my channel. and give me FeedBack.
More Details……
Angularjs Example

Example

I hope you have Got What is Send Email From a Node.JS Script Using SMTP Authentication And how it works.I would Like to have Feed Back From My Blog(Pakainfo.com) readers.Your Valuable Feed Back,Any Question,or any Comments about This Article(Pakainfo.com) Are Most Always Welcome.

Password Protecting Website running on NGinx serve PHP-FPM 0

Password Protecting Website running on NGinx serve PHP-FPM

Password Protecting Website running on NGinx serve PHP-FPM

In this Post We Will Explain About is Password Protecting Website running on NGinx serve PHP-FPM With Example and Demo.Welcome on Pakainfo.com – Examples, The best For Learn web development Tutorials,Demo with Example! Hi Dear Friends here u can know to php – Password protect sub-folder of wordpress website on NginxExample

In this post we will show you Best way to implement How To Set Up Password Authentication with Nginx, hear for How to protect a directory with user and password on Nginxwith Download .we will give you demo,Source Code and examples for implement Step By Step Good Luck!.

Generally here given to the:On ubuntu OS system

nginx config file location

/etc/nginx/sites-available/default

Web-application or site root location default

/usr/share/nginx/www/Pakainfo.com/

htpasswd like as a simple is installed, if not, do

sudo apt-get install apache2-utils

1. Create some users and passwords here

sudo htpasswd -c /usr/share/nginx/www/Pakainfo.com/.htpasswd admin_user
sudo htpasswd  /usr/share/nginx/www/Pakainfo.com/.htpasswd admin_user2

2. Put these to some source commands the nginx config file

auth_basic "Restricted Area”;
auth_basic_user_file /usr/share/nginx/www/Pakainfo.com/.htpasswd;

Some example, if the simple global or config file is /etc/nginx/sites-available/default, path here and then open it

vim /etc/nginx/sites-available/default

Find the some “location /“ and Put these two some lines like As a

location / {
    #some other configurations…
    auth_basic "Restricted Area”;                               
    auth_basic_user_file /usr/share/nginx/www/Pakainfo.com/.htpasswd;
}

3. simple Reload nginx connect configuration and some time to restart nginx

sudo /etc/init.d/nginx reload
sudo service php5-fpm restart

Example

I hope you have Got What is How to password protect a directory with HTTP Authentication in Nginx And how it works.I would Like to have FeadBack From My Blog(Pakainfo.com) readers.Your Valuable FeadBack,Any Question,or any Comments abaout This Article(Pakainfo.com) Are Most Always Welcome.

Cross Header Access Control Allow Origin missing 0

Cross Header Access Control Allow Origin missing

Cross Header Access Control Allow Origin missing

In this Post We Will Explain About is Cross Header Access Control Allow Origin missing With Example and Demo.Welcome on Pakainfo.com – Examples, The best For Learn web development Tutorials,Demo with Example! Hi Dear Friends here u can know to Access Control Allow Origin Error SolutionExample

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://pakainfo.com/api/index.php/driverlist/0. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

1.cross-origin request blocked: (reason: cors header ‘access-control-allow-origin’ missing).
2.this can be fixed by moving the resource to the same domain or enabling cors.
3.cors header ‘access-control-allow-origin’ missing jquery , Angularjs or any ajax call

In this post we will show you Best way to implement reason cors header ‘access-control-allow-origin’ missing angularjs, hear for no access control allow origin header is present jquery ajax originwith Download .we will give you demo,Source Code and examples for implement Step By Step Good Luck!.

AngularJS $http, CORS and http authentication

 $http({
        url: 'http://www.Pakainfo.com/api/v1/get_profile',
        method: "POST",
        data: {username :  ravi dholakiya },
        withCredentials: true,
        headers: {
                    'Content-Type': 'application/json; charset=utf-8'
        }
    });

Nodejs : Access-Control-Allow-Origin

server side you have to put headers nodejs

app.all('*', function(get_request, result,next) {

    var get_response = {
        "AccessControlAllowOrigin": get_request.headers.origin,
        "AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5,  Date, X-Api-Version, X-File-Name",
        "AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
        "AccessControlAllowCredentials": true
    };

    result.header("Access-Control-Allow-Credentials", get_response.AccessControlAllowCredentials);
    result.header("Access-Control-Allow-Origin",  get_response.AccessControlAllowOrigin);
    result.header("Access-Control-Allow-Headers", (get_request.headers['access-control-request-headers']) ? get_request.headers['access-control-request-headers'] : "x-requested-with");
    result.header("Access-Control-Allow-Methods", (get_request.headers['access-control-request-method']) ? get_request.headers['access-control-request-method'] : get_response.AccessControlAllowMethods);

    if ('OPTIONS' == get_request.method) {
        result.send(200);
    }
    else {
        next();
    }

});

config.xml file


.htaccess : Access-Control-Allow-Origin

AngularJS, PHP Restful Cors issue : My .htaccess:

# Cors
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Access-Control-Allow-Origin"
Header always set Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

PHP : Access-Control-Allow-Origin

we are missing CORS settings on your simple PHP headers:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With');
header('Access-Control-Allow-Credentials: true');

Example

I hope you have Got What is Access Control Allow Origin Error Solution And how it works.I would Like to have FeadBack From My Blog(Pakainfo.com) readers.Your Valuable FeadBack,Any Question,or any Comments abaout This Article(Pakainfo.com) Are Most Always Welcome.

Nodejs Real time online users counter using socket io Example 0

Nodejs Real time online users counter using socket io Example

Today, We want to share with you Nodejs Real time online users counter using socket io Example.In this post we will show you Showing online users using Nodejs and Socket.io, hear for Node JS – Get Real time online users counter using socket io example we will give you demo and example for implement.In this post, we will learn about Real time online activity monitor example with node.js and WebSocket with an example.

Nodejs Real time online users counter using socket io Example

There are the Following The simple About Nodejs Real time online users counter using socket io Example Full Information With Example and source code.

first of all You have latest verison installed nodejs, express as well as new socket.io package using npm, As I will cover this Post with live Working example to develop count online users on my website in real time with node.js, so the some major files and Directory structures for this example is following below Steps for real time chat with nodejs socket io and expressjs.

  • index.html
  • server.js

Nodejs Real time online users counter

index.html

This is where I will make a simple HTML form and Node JS server side source code for our web application. To make the forms simply all souce code copy and write it into your any text editor Like Notepad++, then save file it as index.html.

<!DOCTYPE html>
<html>
<head>
   <title>Real time online activity monitor example with node.js and WebSocket</title>
   <script type="text/javascript" src="https://code.jquery.com/jquery-1.4.2.min.js"></script>
   <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script>
</head>

<body>

<h1>socket NodeJS Live Conter : <span id="socket_io_counter"></span></h1>
<b>socket io real time online users example</p>
<script type="text/javascript">
//socket io number of clients in room
  var socket = io.connect('http://localhost:8001');
  socket.on('socket_io_counter', function (response) {
    $("#socket_io_counter").text(response.flags);
  });
</script>
</body>
</html>

Step 2 : Node JS server.js

server.js

Simple Nodejs Real time online users counter for server.js files

var liveapp = require('express')();
var server = require('http').Server(liveapp);
//node js active users counter
var io = require('socket.io')(server);
//nodejs socket.io online users counter
server.listen(8001);
var flags = 0;
var $ipsConnected = [];
io.on('connection', function (socket) {
  var $liveIpAddress = socket.handshake.address;
  //check socket io online users
  if (!$ipsConnected.hasOwnProperty($liveIpAddress)) {
  	$ipsConnected[$liveIpAddress] = 1;
  	flags++;
	//socket io real time online users example
  	socket.emit('socket_io_counter', {flags:flags});
  }
  console.log("Good Luck, client is connected");
  /* Your Live (socket.io client flags) Disconnect socket */
  socket.on('disconnect', function() {
  	if ($ipsConnected.hasOwnProperty($liveIpAddress)) {
  		delete $ipsConnected[$liveIpAddress];
	    flags--;
	    socket.emit('socket_io_counter', {flags:flags});
  	}
  });
});

Save And run server.js file

run Project and Nodejs Get Real time online users counter using socket io Example

//Nodejs Real time online users counter
nodejs server.js

Nodejs Real time online users counter using socket io – Output

Nodejs Real time online users counter - Nodejs Real time online users counter using socket io Example

Nodejs Real time online users counter

Angular 6 CRUD Operations Application Tutorials

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about Nodejs Real time online users counter using socket io Example.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Angular 6 CRUD Operations Demo Example 0

Angular 6 CRUD Operations Demo Example

Today, We want to share with you Angular 6 CRUD Operations Demo Example.In this post we will show you Angular 6 CRUD Tutorial for beginners, hear for Angular 6 CRUD Operations Application and Example we will give you demo and example for implement.In this post, we will learn about Angular 6 CRUD Project Setup, Routing, Service with an example.

Angular 6 CRUD Operations Demo Example

There are the Following The simple About Angular 6 CRUD Operations Demo Example Full Information With Example and source code.

As I will cover this Post with live Working example to develop , so the some major files and Directory structures for this example is following below.

  • Angular 6 Install Angular CLI.
  • Angular 6 Project Setup
  • Angular 6 components
  • Angular 6 Configure Routing
  • Angular 6 Project
  • Add Bootstrap CSS
  • HttpClientModule in Angular 6
  • More..

Angular 6 CRUD Example Tutorial From Scratch

Step 1: Install Angular CLI in Angular 6 Project.

Install Angular CLI

npm install -g @angular/cli

create a local project in Angular 6

ng new angular6crud

Angular 6 start the application

ng serve --open

Step 2: Make three components.

components inside app folder

Simple Angular 6 CRUD Operations Demo Installations

Angular 6 CRUD Example Tutorial From Scratch - Angular 6 CRUD Operations Demo Example

Angular-6-CRUD-Example-Tutorial-From-Scratch

Step 3: Configure the routing in Angular 6.

app.module.ts

// app.module.ts

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

//Angular 6 CRUD Operations Demo Routing
const routes:Routes = [
  { 
    path: 'create', 
    component: CreateComponent 
  },
  {
    path: 'edit/:id',
    component: EditComponent
  },
  { 
    path: 'index',
    component: IndexComponent
  }
]

register these routes

// app.module.ts

imports: [
    BrowserModule,
    RouterModule.forRoot(routes)
],

in Angular 6 router-outlet> inside an source code of app.component.html file

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

Step 4: Insert Bootstrap CSS.

src >> index.html

<link rel="stylesheet" href="assets/css/bootstrap.min.css">

app.component.html

<nav class="navbar navbar-default">
  <div class="container-fluid">
    <ul class="nav navbar-nav">
      <li class="active">
        <a routerLink="create" routerLinkActive="active">
          Add Members
        </a>
      </li>    
    </ul>
  </div>
</nav>

<div class="container">
  <router-outlet></router-outlet>
</div>

Step 5: Create a HTML form in the make a component file.

create.component.html

<h2>Angular 6 CRUD Operations Demo</h2>
<div class="card">
    <div class="card-body">
      <form>
        <div class="form-group">
          <label class="col-md-4">Member Name</label>
          <input type="text" class="form-control" name="member_name"/>
        </div>
        <div class="form-group">
          <label class="col-md-4">Member Age</label>
          <input type="text" class="form-control" name="member_age"/>
          </div>
          <div class="form-group">
            <button type="submit" class="btn btn-success">Add</button>
          </div>
      </form>
    </div>
  </div>

Step 6: Configure angular 6 HttpClientModule.

app.module.ts

// app.module.ts
//Angular 6 CRUD Operations Demo

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

imports: [
    BrowserModule, RouterModule.forRoot(appRoutes), HttpClientModule
],

step 7: Make services to send angular 6 http requests.

ng g service member

MemberService.ts

// MemberService.ts

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

@Injectable({
  providedIn: 'root'
})
export class MemberService {

  constructor() { }
}

member.service.ts

// member.service.ts

import { MemberService } from './member.service';

providers: [ MemberService ]

Step 8: Configure Node.js backend.

Node.js as well as MongoDB backend for Angular 6 CRUD Operations Demo

//express web framework
npm install --save express body-parser cors mongoose


//add nodemon server 
npm install nodemon --save-dev

app.js

let express = require('express'),
    path = require('path'),
    bodyParser = require('body-parser'),
    cors = require('cors'),
    mongoose = require('mongoose');

    const app = express();
    var port = process.env.PORT || 4000;

    var server = app.listen(function(){
        console.log('Listening on port ' + port);
    });

DB.js

// DB.js

module.exports = {
   DB: 'mongodb://localhost:27017/angular6crud'
};

copy and paste the Angular 6 CRUD Operations Demo following source code inside the main file server.js In to connect step by step simple main MongoDB store database application to the main files like as Node.js server.

// server.js

const express = require('express'),
    path = require('path'),
    bodyParser = require('body-parser'),
    cors = require('cors'),
    mongoose = require('mongoose'),
    config = require('./config/DB');

    mongoose.Promise = global.Promise;
    mongoose.connect(config.DB).then(
      () => {console.log('Database is connected') },
      err => { console.log('Can not connect to the database'+ err)}
    );

    const app = express();
    app.use(bodyParser.json());
    app.use(cors());
    const port = process.env.PORT || 4000;

    const server = app.listen(port, function(){
     console.log('Listening on port ' + port);
    });

node.js run command

nodemon server

And then, I have All the three main servers are running.

  • Angular Development Server.
  • simple Node.js Server
  • start Mongodb Server

Step 9: Make Express routes for angular 6 Web application.

Member.js

// Member.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Define collection and schema for Members
let Member = new Schema({
  name: {
    type: String
  },
  age: {
    type: Number
  }
},{
    collection: 'members'
});

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

member.route.js

// member.route.js

const express = require('express');
const app = express();
const memberRoutes = express.Router();

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

memberRoutes.route('/add').post(function (request, response) {
  let member = new Member(request.body);
   member.save()
    .then(member => {
    response.status(200).json({'member': 'CoMemberin added successfully'});
    })
    .catch(err => {
    response.status(400).send("unable to save to database");
    });
});


memberRoutes.route('/').get(function (request, response) {
   Member.find(function (err, members){
    if(err){
      console.log(err);
    }
    else {
      response.json(members);
    }
  });
});

memberRoutes.route('/edit/:id').get(function (request, response) {
  let id = request.params.id;
  Member.findById(id, function (err, member){
      response.json(member);
  });
});

//  Defined update route
memberRoutes.route('/update/:id').post(function (request, response) {
   Member.findById(request.params.id, function(err, member) {
    if (!member)
      return next(new Error('Could not load Document'));
    else {
      member.name = request.body.name;
      member.age = request.body.age;

      member.save().then(member => {
          response.json('Update complete');
      })
      .catch(err => {
            response.status(400).send("unable to update the database");
      });
    }
  });
});

// Defined delete | remove | destroy route
memberRoutes.route('/delete/:id').get(function (request, response) {
   Member.findByIdAndRemove({_id: request.params.id}, function(err, member){
        if(err) response.json(err);
        else response.json('Successfully removed');
    });
});

module.exports = memberRoutes;

Add this simple Member.js model inside a main server.js file.

// server.js

const memberRoutes = require('./routes/member.route');

app.use('/members', memberRoutes);

server.js

// server.js

const express = require('express'),
    path = require('path'),
    bodyParser = require('body-parser'),
    cors = require('cors'),
    mongoose = require('mongoose'),
    config = require('./config/DB');

const memberRoutes = require('./routes/member.route');

    mongoose.Promise = global.Promise;
    mongoose.connect(config.DB).then(
      () => {console.log('Database is connected') },
      err => { console.log('Can not connect to the database'+ err)}
    );

const app = express();
    app.use(bodyParser.json());
    app.use(cors());
    app.use('/members', memberRoutes);

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

const server = app.listen(port, function(){
    console.log('Listening on port ' + port);
});

Step :10 Insert ReactiveFormsModule at the Angular 6


// app.module.ts

import { ReactiveFormsModule } from '@angular/forms';

imports: [
    ReactiveFormsModule
  ],

create.component.html

<div class="card">
    <div class="card-body">
      <form [formGroup]="memberFrm" novalidate>
        <div class="form-group">
          <label class="col-md-4">Member Name</label>
          <input type="text" class="form-control" formControlName="name" #name />
        </div>
        <div *ngIf="memberFrm.controls['name'].invalid && (memberFrm.controls['name'].dirty || memberFrm.controls['name'].touched)" class="alert alert-danger">
          <div *ngIf="memberFrm.controls['name'].errors.required">
            Name is required.
          </div>
        </div>
        <div class="form-group">
          <label class="col-md-4">Member Age</label>
          <input type="text" class="form-control" formControlName="age" #age/>
        </div>
        <div *ngIf="memberFrm.controls['age'].invalid && (memberFrm.controls['age'].dirty || memberFrm.controls['age'].touched)" class="alert alert-danger">
          <div *ngIf="memberFrm.controls['age'].errors.required">
            Age is required.
          </div>
        </div>
          <div class="form-group">
            <button (click)="addMember(name.value, age.value)" [disabled]="memberFrm.pristine || memberFrm.invalid" class="btn btn-success">Add</button>
          </div>
      </form>
    </div>
  </div>

create.component.ts

// create.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';
import { MemberService } from '../../member.service';

@Component({
  selector: 'app-create',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {

 title = 'Add Member';
  memberFrm: FormGroup;

  constructor(private memberservice: MemberService, private fb: FormBuilder) {
    this.createForm();
   }

   createForm() {
    this.memberFrm = this.fb.group({
      name: ['', Validators.required ],
      age: ['', Validators.required ]
   });
  }

  addMember(name, age) {
      this.memberservice.addMember(name, age);
  }

  ngOnInit() {
  }

}

member.service.ts

// member.service.ts

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

@Injectable({
  providedIn: 'root'
})
export class MemberService {

  constructor(private http: HttpClient) { }

  addMember(name, age) {
    const uri = 'http://localhost:4000/members/add';
    const obj = {
      name: name,
      age: age
    };
    this.http.post(uri, obj)
        .subscribe(response => console.log('Done'));
  }
}

Step 10: Listing the data content to the View Side.

index.component.html

<table class="table table-hover">
  <thead>
  <tr>
      <td>Member Name</td>
      <td>Member Age</td>
      <td colspan="2">Actions</td>
  </tr>
  </thead>

  <tbody>
      <tr *ngFor="let member of members">
          <td>{{ member.name }}</td>
          <td>{{ member.age }}</td>
          <td><a [routerLink]="['/edit', member._id]" class="btn btn-success">Edit</a></td>
          <td><a [routerLink]="" class="btn btn-danger">Delete</a></td>
      </tr>
  </tbody>
</table>

Member.ts

export interface Member {
    id: Number;
    name: String;
    age: Number;
}

member.service.ts

And then, inside member.service.ts file, I should to simple a function that get the data from the latest light weight json based MongoDB database and listing at the first Angular 6 Application.

// member.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Member } from './components/index/Member';

@Injectable({
  providedIn: 'root'
})
export class MemberService {

    const uri = 'http://localhost:4000';

 	constructor(private http: HttpClient) { }

  	addMember(name, age) {
        const obj = {
          name: name,
          age: age
        };
        this
        	.http
        	.post(`${this.uri}/members/add`, obj)
            .subscribe(response => 
            	console.log('Done')
            );
  	}

  	getMembers() {
             return this
                    .http
                    .get(`${this.uri}/members`);
    	}
 }
}

index.component.ts

// index.component.ts

import { Component, OnInit } from '@angular/core';
import { Member } from './Member';
import { MemberService } from '../../member.service';

@Component({
  selector: 'app-index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.css']
})
export class IndexComponent implements OnInit {

    members: Member[];

 	constructor(private memberservice: MemberService) { }

  	ngOnInit() {
  		this.memberservice
      		.getMembers()
      		.subscribe((data: User[]) => {
        		this.members = data;
        });
    }
}

Run this project http://localhost:4200/index.

Step 11: Angular 6 Edit and Update the Data.

edit.component.html

<div class="card">
    <div class="card-body">
      <form [formGroup]="memberFrm" novalidate>
        <div class="form-group">
          <label class="col-md-4">Member Name</label>
          <input type="text" class="form-control" formControlName="name" #name [(ngModel)] = "member.name"/>
        </div>
        <div *ngIf="memberFrm.controls['name'].invalid && (memberFrm.controls['name'].dirty || memberFrm.controls['name'].touched)" class="alert alert-danger">
          <div *ngIf="memberFrm.controls['name'].errors.required">
            Name is required.
          </div>
        </div>
        <div class="form-group">
          <label class="col-md-4">Member Age</label>
          <input type="text" class="form-control" formControlName="age" #age [(ngModel)] = "member.age"/>
        </div>
        <div *ngIf="memberFrm.controls['age'].invalid && (memberFrm.controls['age'].dirty || memberFrm.controls['age'].touched)" class="alert alert-danger">
          <div *ngIf="memberFrm.controls['age'].errors.required">
            Age is required.
          </div>
        </div>
          <div class="form-group">
            <button (click)="updateMember(name.value, age.value)" [disabled]="memberFrm.pristine || memberFrm.invalid" class="btn btn-success">Add</button>
          </div>
      </form>
    </div>
  </div>

Inside edit.component.ts

// edit.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';
import { MemberService } from '../../member.service';
import { Member } from '../index/Member';

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {

    member: any = {};
    memberFrm: FormGroup;
    constructor(private route: ActivatedRoute, 
                private router: Router, 
                private service: MemberService, 
                private fb: FormBuilder) { 
        this.createForm();
    }

    createForm() {
    this.memberFrm = this.fb.group({
         	name: ['', Validators.required ],
          	age: ['', Validators.required ]
   		});
  	}

    ngOnInit() {
        this.route.params.subscribe(params => {
     		this.service.editMember(params['id']).subscribe(response => {
        		this.member = response;
      	});
    });
  }
}

edit.component.ts

// edit.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';
import { MemberService } from '../../member.service';
import { Member } from '../index/Member';

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {

    member: any = {};
    memberFrm: FormGroup;
    constructor(private route: ActivatedRoute, 
                private router: Router, 
                private service: MemberService, 
                private fb: FormBuilder) { 
        this.createForm();
    }

    createForm() {
    this.memberFrm = this.fb.group({
         	name: ['', Validators.required ],
          	age: ['', Validators.required ]
   		});
  	}

    ngOnInit() {
        this.route.params.subscribe(params => {
     		this.service.editMember(params['id']).subscribe(response => {
        		this.member = response;
      	});
    });
  }
}

member.service.ts

// member.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Member } from './components/index/Member';

@Injectable({
  providedIn: 'root'
})
export class MemberService {

    uri = 'http://localhost:4000/members';

 	constructor(private http: HttpClient) { }

  	addMember(name, age) {
        const obj = {
          name: name,
          age: age
        };
        this
        	.http
        	.post(`${this.uri}/add`, obj)
            .subscribe(response => 
            	console.log('Done')
            );
  	}

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

    editMember(id) {
    	return this
            .http
            .get(`${this.uri}/edit/${id}`)
    	}
 }

member.service.ts

After, update All the data content. then simple the following source code inside member.service.ts file. O will write step by step the update angular 6 function inside member.service.ts file.

// member.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Member } from './components/index/Member';

@Injectable({
  providedIn: 'root'
})
export class MemberService {

  uri: String = 'http://localhost:4000/members';

  constructor(private http: HttpClient) { }

  addMember(name, age) {
        const obj = {
          name: name,
          age: age
        };
        this
        	.http
        	.post(`${this.uri}/add`, obj)
            .subscribe(response => 
            	console.log('Done')
            );
  	}

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

   editMember(id) {
    	return this
            .http
            .get(`${this.uri}/edit/${id}`)
    	}

   updateMember(name, age, id) {

      const obj = {
      name: name,
       age: age
       };
    this
       .http
       .post(`${this.uri}/update/${id}`, obj)
       .subscribe(response => console.log('Done'));
  	}
}

edit.component.ts

After that, simple the following source code inside edit.component.ts main file.

// edit.component.ts

updateMember(name, age) {
     this.route.params.subscribe(params => {
     this.service.updateMember(name, age, params['id']);
     this.router.navigate(['index']);
  });
}

index.component.html

Lets start, We are source coding the All the main simple index.component.html file.

<tbody>
      <tr *ngFor="let member of members">
          <td>{{ member.name }}</td>
          <td>{{ member.age }}</td>
          <td><a [routerLink]="['/edit', member._id]" class="btn btn-success">Edit</a></td>
          <td><button (click)="deleteMember(member._id)"  class="btn btn-danger">Delete</button></td>
      </tr>
</tbody>

index.component.ts

And then, write the deleteMember function inside main root Angular 6 index.component.ts file.

// index.component.ts

import { Component, OnInit } from '@angular/core';
import { Member } from './Member';
import { MemberService } from '../../member.service';

@Component({
  selector: 'app-index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.css']
})
export class IndexComponent implements OnInit {

    members: Member[];

    constructor(private memberservice: MemberService) { }

    ngOnInit() {
  	this.memberservice
      	    .getMembers()
      	    .subscribe((data: Member[]) => {
        	this.members = data;
        });
   }

   deleteMember(id) {
     this.memberservice.deleteMember(id).subscribe(response => {
      console.log('Deleted');
    });
   }
}

Lastly, simple the deleteMember function inside member.service.ts file.

member.service.ts

// member.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Member } from './components/index/Member';

@Injectable({
  providedIn: 'root'
})
export class MemberService {

    uri: String = 'http://localhost:4000/members';

 	constructor(private http: HttpClient) { }

  	addMember(name, age) {
        const obj = {
          name: name,
          age: age
        };
        this
        	.http
        	.post(`${this.uri}/add`, obj)
            .subscribe(response => 
            	console.log('Done')
            );
  	}

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

    editMember(id) {
    	return this
            .http
            .get(`${this.uri}/edit/${id}`)
    	}

 	updateMember(name, age, id) {

        const obj = {
            name: name,
            age: age
        };
        this
        	.http
        	.post(`${this.uri}/update/${id}`, obj)
         	.subscribe(response => console.log('Done'));
  	}

  	deleteMember(id) {
  		return this
            .http
            .get(`${this.uri}/delete/${id}`)
  	}
}

If you have any stuck or problems in Angular 6 CRUD Insert Update delete operations, then you freely ask in a this comment below.

Angular 6 CRUD Example Tutorial
Angular 6 CRUD Operations Application Tutorials

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about Angular 6 CRUD Example Tutorial From Scratch.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.