Topic: Node.js

Basic Computer Programming Languages Principles 0

Basic Computer Programming Languages Principles

Today, We want to share with you Basic Computer Programming Languages Principles.
In this post we will show you Programming principles, hear for The Principles Of Good Programming we will give you demo and example for implement.
In this post, we will learn about Basic Programming Principles Every Programmer Must Follow with an example.

Overview

Programming principles have helped me over the years in becoming a better programmer and developer, and I also believe, this article will help every developer become more efficient and able to produce code which is easier to maintain. By following these coding and programming principles, you can save development and maintenance time, and conquer lots of other congestion which may arise in later development phases.

What are Programming principles?

Programming is the complete process, which involves various stages such as coding, testing, debugging and maintaining a system.Programming principles assist you to write good quality of code and maintain a good coding practice.

Why should a developer follow it?

Actually, writing programs is mostly a matter of personal taste but there are certain rules or guidelines that should be followed within your style of code in order to make programs easy to maintain and understand by both, you and others(your team), and also principles guide the creation of Optimized, scalable, easy to maintain, and robust code.

What are the benefits if developer follows Programming principles?

Readability

All developers which are in a team of project able to understand the code.

Extensibility

In the Software world, changes are needed on time to time, If we have followed rule properly then it will become very easy to implement new changes in software.

Maintainability

It becomes easy to maintain by the development team and the production support team too because the application is loosely coupled.

Modularity

Make a whole program into small reusable pieces: functions, modules, libraries,union, structures.

Conclusion

  • You should write a program that is self-explanatory.
  • Use Comment wherever required, It makes documentation easy.
  • You should write a code which should be easy to maintain among your team.
jQuery 15 Powerful Tips and Tricks for Developers and Web Designer

Apart from this properly written program would also be easy to debug.
These principles will help you and others in the team to write or deliver good, clean, and high-quality code.

Read :

Summary

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

I hope you get an idea about Computer Programming Principles.
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.

SSL forcefully Redirect HTTP to HTTPS Using .htaccess File 0

SSL forcefully Redirect HTTP to HTTPS Using .htaccess File

Today, We want to share with you SSL forcefully Redirect HTTP to HTTPS Using .htaccess File.In this post we will show you How to force SSL using the .htaccess file , hear for How to redirect HTTP traffic to HTTPS using an .htaccess file we will give you demo and example for implement.In this post, we will learn about Redirecting HTTP to HTTPS Using .htaccess File: Step by Step with an example.

SSL forcefully Redirect HTTP to HTTPS Using .htaccess File

There are the Following The simple About SSL forcefully Redirect HTTP to HTTPS Using .htaccess File Full Information With Example and source code.

As I will cover this Post with live Working example to develop Force your site to load securely with an .htaccess file, so the some Redirect HTTP to HTTPS automatically for this example is following below.

Step 1: first of all simple Editing your .htaccess in main cPanel goto File Manager

Step 2: Sign In to cPanel

Step 3: and then Go to The Files > your File Manager > and Document main Root for:

Step 4: After that choose the tour domain name We want to get access

Step 5: Now a new open tab or window main file opens, look for the name as a .htaccess file.

Step 6: .htaccess redirect http to https

Redirecting HTTP to HTTPS Using .htaccess File

RewriteEngine on

# force ssl
RewriteCond     %{SERVER_PORT} ^80$
RewriteRule     ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]

Note: Please get Your .htaccess file and all the Backup your main Data website in case all the something goes wrong.

Redirect All Web Traffic

RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://www.myDomainName.com/$1 [R,L]

Redirect Only a Specific Domain

Simple redirecting a specific main My domain Working on SSL forcefully to use HTTPS

RewriteEngine On 
RewriteCond %{HTTP_HOST} ^myDomainName\.com [NC]
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://www.myDomainName.com/$1 [R,L]

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 SSL forcefully Redirect HTTP to HTTPS Using .htaccess File.
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.

nodejs Installation Steps on windows 0

nodejs Installation Steps on windows

Today, We want to share with you nodejs Installation Steps on windows.In this post we will show you Installing Node.js Tutorial: Windows, hear for How to Install Node.Js on Windows we will give you demo and example for implement.In this post, we will learn about Installing Node.js® and NPM on Windows with an example.

What is Node.js?

Node.js is a one type of platform built on Chrome’s(Browser’s) JavaScript runtime for most easily buildipakainfo easy and fast and scalable network app’s.
Node.js uses the most way to an event-driven programs, non-blockipakainfo I/O model and that makes it lightweight data and efficient data, and perfect data for data-intensive apps and real-time app’s that run across distributed devices. Node.js used mostly Sipakainfole Page Applications(spa’s) and JSON APIs created Applications.

Node.js Means = Runtime Environment + JavaScript Library = Node.js

List of Node.js Features

Node.js is Asynchronous and Event Driven.
and It’s very Fast other javascript. and It’s Sipakainfole Threaded but Highly Scalable. and node.js is never/No Bufferipakainfo data.It’s Include License .

Installation Overview :Local Environment Setup

  • Text Editor(Like Notepad.)
  • OS Edit command
  • Linux or UNIX.

Installation Steps

Step : 1 simple easy to Download the Windows OS installer from (JavaScript Frameworks)the Nodes.js® web site or click this button here.

Node.js – Download

Step : 2 and Now the Run the installer this file (the .msi file you simple easy way to downloaded in the previous step.)

Step : 3 Now,Follow the cmd prompts in the installer and check (Accept all the license agreement and terms and conditions, and check the click the NEXT button and a bunch of all times and select accept the default installation settipakainfos default settipakainfos).

Step : 4 Now Last step is the Restart your computer or shut down your computer. You won’t be able to here run Node.js® frameworks until you restart your computer and test is this command.

Node.js : Test it!

node -v
/or/
npm - v

How to Open URL in New Tab using ReactJS 0

How to Open URL in New Tab using ReactJS

Today, We want to share with you How to Open URL in New Tab using ReactJS.
In this post we will show you react-router-link-target, hear for Passing object to a new tab/window using ReactJS we will give you demo and example for implement.In this post, we will learn about Open link in new tab in react router programmatically with an example.

My Paka Knowledgeable Ideas, Tips and Tricks, Useful Content, Jobs, Technology, Earn Money, gmail creation, skype, yahoo and more useful things.

In ReactJS, Open new window when target=”_blank”

About Pakainfo.com

ReactJS Overview with Features

There are the Following the List of Features For ReactJS Pure JavaScript Latest Frameworks.

  • Adaptability
  • SCMAScript
  • Decorators from ES7
  • Server-side Communication
  • Light Railing for Applications
  • Asynchronous Functions
  • Generators
  • Usefulness of JSX
  • Flux Library
  • Free and Open Source
  • Destructuring Assignments

ReactJS redirect to a new tab

Open link in new tab in react router programmatically

//HTML Part
<div>Something To Click On</div>

//ReactJS Part

<a target='_blank' href="{this.makeHref(routeConsts.CHECK_DOMAIN,">
        Share this link to your webmaster
</a>

//You Can Use for ReactJS
 {event.preventDefault(); window.open(this.makeHref("route"));}} />

ReactJS Redirects

<div id="app"></div>

var ReactRouter = ReactReactRouter;
var Route = ReactRouter.Route, 
		DefaultRoute = ReactRouter.DefaultRoute,
  	Link=ReactRouter.Link, 
    RouteHandler = ReactRouter.RouteHandler;

var App = React.createClass({
  mixins: [ReactRouter.State],
  componentDidMount: function() {
  },
  render: function() {
    var name = this.getRoutes().reverse()[0].name;

    return (
      <div>
        <ul>
            <li>ContactUs link</li>    
            <li>AboutUs link</li>    
        </ul>
        
      </div>
    );
  }
});
          
var ContactUs = React.createClass({
    componentWillLeave: function(param) {
      console.log('ContactUs will leave');
      setTimeout(param, 1);
    },
    componentDidMount: function(param) {
      console.log('ContactUs will open');
    },
    render: function() {
        return (
          <div>ContactUs 1 content</div>
        );
    }          
});
          
var AboutUs = React.createClass({
    componentWillLeave: function(param) {
      console.log('AboutUs will leave');
      setTimeout(param, 1);
    },
    componentDidMount: function(param) {
      console.log('AboutUs will open');
    },
    render: function() {
        return (
          <div>AboutUs 2 content</div>
        );
    }          
});
    
var routes = (
  
    
    
  
);

ReactRouter.run(routes, function (Handler) {
  React.render(, document.getElementById('app'));
});
    

ReactJS Redirecting To External Domains

React redirect to external url Example

handleClick() {
  // do something react js meaningful, more useful Promises, conditions if/else, whatever, and then
  window.location.assign('https://pakainfo.com');
}

jQuery 15 Powerful Tips and Tricks for Developers and Web Designer

Read :

Summary

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

I hope you get an idea about react open link in new tab programmatically.
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.

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].com',
          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.

How to uninstall cordova and ionic in ubuntu 0

How to uninstall cordova and ionic in ubuntu

How to uninstall cordova and ionic in ubuntu

In this Post We Will Explain About is How to uninstall cordova and ionic in ubuntu 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 do you completely remove Ionic and Cordova
Example

In this post we will show you Best way to implement How do you completely remove Ionic and Cordova installation, hear for Install Android, Cordova, And Ionic Framework In Ubuntuwith Download .we will give you demo,Source Code and examples for implement Step By Step Good Luck!.

If We require to simple remove cordova data and ionic data from ubuntu then We simple uninstall using terminal data command. We can help to uninstall cordova step by stepthen We can just simple run bellow example to command.

Example:

sudo npm uninstall -g cordova

sudo npm uninstall -g ionic

I added simple two command one for all the uninstall cordova and other simple uninstall ionic js framework.

npm uninstall cordova ionic

npm cache clean -f
npm install npm -g

npm uninstall node
apt-get purge npm
apt-get install npm
npm install node -g

Use bellow command for uninstall ionic and corova

uninstall :

sudo npm uninstall -g cordova

sudo npm uninstall -g ionic

install :

sudo npm install -g cordova

Command to remove simple Cordova and ionic

Latest simple Window system

	npm uninstall -g ionic
	npm uninstall -g cordova

Latest simple Mac system
	sudo npm uninstall -g ionic
	sudo npm uninstall -g cordova

Latest simple install cordova and ionic
	npm install -g cordova
	npm install -g ionic

Example

I hope you have Got What is How to uninstall Ionic framework from NodeJS in Windows 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.

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

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