Quick Contact

    Life Cycle Hooks in MEAN Stack

    We learnt about the service and how to make the angular aware of it in the previous section. In the postService class, we added getPosts and addPost methods. We’ll learn how to use the getPosts and addPost functions in this section. We’ll also look at the user interface.

    When Angular builds a component, it includes lifecycle hooks, which are immediately executed. One of the lifecycle hooks we utilise in our programme is onInit.

    The onInit interface class is an interface class. As a result, we’ll implement it as well as override its abstract function, ngOnInit().When Angular creates this component, it executes this function for us. This will be done in the following manner:

    Module.js File:-
    
    	var main = angular.module("main", ['ui.router','ngRoute','ngResource'])
    	.run(function($http,$rootScope)
    	{
    	if(sessionStorage.length> 0){
    	        $rootScope.current_user = sessionStorage.current_user;
    	        $rootScope.authenticated = true;
    	}else{
    	        $rootScope.authenticated = false;
    	        $rootScope.current_user = 'Guest';
    	    }
    
    	    $rootScope.signout = function(){
    	        $http.get('auth/signout');
    	        $rootScope.authenticated = false;
    	        $rootScope.current_user = 'Guest';
    	sessionStorage.clear();
    	    };
    
    	});                                                                                                     
    	//Routing Configuration (define routes)
    	main.config([
    	    '$stateProvider', '$urlRouterProvider', '$httpProvider',
    	function ($stateProvider, $urlRouterProvider,$rootScope) {
    	        $urlRouterProvider.otherwise('/');
    	        $stateProvider
    	            .state('home', {
    	url: '/',
    	templateUrl: 'Index.html',
    	caseInsensitiveMatch: true,
    	controller: 'MainController'
    	            })
    	            .state('contact', {
    	url: '/contact',
    	templateUrl: 'Contact.html',
    	caseInsensitiveMatch: true,
    	controller: 'MainController'
    	            })
    	            .state('about', {
    	url: '/about',
    	templateUrl: 'About.html',
    	caseInsensitiveMatch: true,
    	controller: 'MainController'
    	            })
    	            .state('login',{
    	url: '/login',
    	templateUrl: 'login.html',
    	caseInsensitiveMatch: true,
    	controller: 'AuthController'
    	            })
    	            .state('register',{
    	function ($stateProvider, $urlRouterProvider,$rootScope) {
    	        $urlRouterProvider.otherwise('/');
    	        $stateProvider
    	            .state('home', {
    	url: '/',
    	templateUrl: 'Index.html',
    	caseInsensitiveMatch: true,
    	controller: 'MainController'
    	            })
    	            .state('contact', {
    	url: '/contact',
    	templateUrl: 'Contact.html',
    	caseInsensitiveMatch: true,
    	controller: 'MainController'
    	            })
    	            .state('about', {
    	url: '/about',
    	templateUrl: 'About.html',
    	caseInsensitiveMatch: true,
    	controller: 'MainController'
    	            })
    	            .state('login',{
    	url: '/login',
    	function ($stateProvider, $urlRouterProvider,$rootScope) {
    	        $urlRouterProvider.otherwise('/');
    	        $stateProvider
    	            .state('home', {
    	url: '/',
    	templateUrl: 'Index.html',
    	caseInsensitiveMatch: true,
    	controller: 'MainController'
    	            })
    	            .state('contact', {
    	url: '/contact',
    	templateUrl: 'Contact.html',
    	caseInsensitiveMatch: true,
    	controller: 'MainController'
    	            })
    	            .state('about', {
    	url: '/about',
    	templateUrl: 'About.html',
    	caseInsensitiveMatch: true,
    	controller: 'MainController'
    	            })
    	            .state('login',{
    	url: '/login',
    	url: '/register',
    	templateUrl: 'register.html',
    	caseInsensitiveMatch: true,
    	controller: 'AuthController'
    	            }).state('unauth',{
    	url: '/unauth',
    	templateUrl: 'unauth.html',
    	caseInsensitiveMatch: true
    	            });
    	    }
    	]);
    	

    Now we’ll use the addPost() method or function. We’ll return to the file post-create.component.ts. We’ll use a function Object() { [native code] } to link this file to our service, just like we did with our post-list.component.ts file. We don’t utilise emitter and output anymore. We delete both of them from our code and use the following syntax to call the addPost(0) functions:

    The MEAN stack is a set of JavaScript-based technologies that are used to create online applications. MongoDB, ExpressJS, AngularJS, and Node.js are referred to as MEAN. MEAN is full stack JavaScript, from client to server to database.

    Let me explain how they interact. Angular is mostly used for front-end development. I’ll use Angular.js to create views that can be rendered on a single page. On the server side, I’ll use Node.js, which uses Express.js internally. Using Express, I’ll create an API to connect with the database. In the end, I’ll store my data in MongoDb. As seen in the diagram

    
    	import{PostService} from '../posts.service';  
    	export class PostCreateComponent {  
    	enteredTitle = "";  
    	enteredContent = "";  
    
    	constructor(public postsService: PostService){}  
    
    	onAddPost( form: NgForm){  
    	if(form.invalid){  
    	return;  
    	      }  
    	this.postsService.addPost(form.value.title, form.value.content )  
    	main.controller("AuthController", function ($scope, $http, $rootScope, $location) {
    	$scope.user = {username: '', password: ''};
    	$scope.error_message = '';
    
    	$scope.login = function(){
    	        $http.post('/auth/login', $scope.user).success(function(data){
    	if(data.state == 'success'){
    	                $rootScope.authenticated = true;
    	                $rootScope.current_user = data.user.username;
    	                $rootScope.sess = data.user;
    	sessionStorage.setItem('current_user', $rootScope.sess.username);
    	                $location.path('/');
    	                }
    	else{
    	                $scope.error_message = data.message;
    	                $rootScope.sess = null;
    	            }
    	        });
    	$http.post('/auth/login', $scope.user).success(function(data){
    	if(data.state == 'success'){
    	                $rootScope.authenticated = true;
    	                $rootScope.current_user = data.user.username;
    	                $rootScope.sess = data.user;
    	sessionStorage.setItem('current_user', $rootScope.sess.username);
    	                $location.path('/');
    	$http.post('/auth/login', $scope.user).success(function(data){
    	if(data.state == 'success'){
    	                $rootScope.authenticated = true;
    	                $rootScope.current_user = data.user.username;
    	                $rootScope.sess = data.user;
    	sessionStorage.setItem('current_user', $rootScope.sess.username);
    	                $location.path('/');
    
    	$scope.register = function(){
    	console.log($scope.user);
    	        $http.post('/auth/signup', $scope.user).success(function(data){
    	if(data.state == 'success'){
    	                $rootScope.authenticated = true;
    	                $rootScope.current_user = data.user.username;
    	                $location.path('/');$scope.register = function(){
    	console.log($scope.user);
    	        $http.post('/auth/signup', $scope.user).success(function(data){
    	if(data.state == 'success'){
    	                $rootScope.authenticated = true;
    	                $rootScope.current_user = data.user.username;
    	                $location.path('/');$scope.register = function(){
    	console.log($scope.user);
    	        $http.post('/auth/signup', $scope.user).success(function(data){
    	if(data.state == 'success'){
    	                $rootScope.authenticated = true;
    	                $rootScope.current_user = data.user.username;
    	                $location.path('/');
    	$http.post('/auth/login', $scope.user).success(function(data){
    	if(data.state == 'success'){
    	                $rootScope.authenticated = true;
    	                $rootScope.current_user = data.user.username;
    	                $rootScope.sess = data.user;
    	sessionStorage.setItem('current_user', $rootScope.sess.username);
    	                $location.path('/');
    	$http.post('/auth/login', $scope.user).success(function(data){
    	if(data.state == 'success'){
    	                $rootScope.authenticated = true;
    	                $rootScope.current_user = data.user.username;
    	                $rootScope.sess = data.user;
    	sessionStorage.setItem('current_user', $rootScope.sess.username);
    	                $location.path('/');
    	$http.post('/auth/login', $scope.user).success(function(data){
    	if(data.state == 'success'){
    	                $rootScope.authenticated = true;
    	                $rootScope.current_user = data.user.username;
    	                $rootScope.sess = data.user;
    	sessionStorage.setItem('current_user', $rootScope.sess.username);
    	                $location.path('/');
    	};
    	  //login call to webapi (node implemented service)
    	    $scope.register = function(){
    	console.log($scope.user);
    	        $http.post('/auth/signup', $scope.user).success(function(data){
    	if(data.state == 'success'){
    	                $rootScope.authenticated = true;
    	                $rootScope.current_user = data.user.username;
    	                $location.path('/');
    	            }
    	else{
    	                $scope.error_message = data.message;
    	            }
    	        });
    	    };
    	});
    	

    Angular JS is a JavaScript framework that is open-source. Google is in charge of Angular. This framework’s objective is to integrate MVC (Model View Controller) architecture to browser-based applications, making development and testing easier. The framework aids in the development of a smarter web app that allows for customisation.

    We may utilise HTML as a template language with AngularJS. As a result, you may use HTML’s syntax to represent your application’s components. Dependency injection and data binding are two Angular capabilities that minimise the need to write a lot of code.

    Let’s make some renderable views. Create a new folder Views and add the following ejs code to the main directory, as ejs is the render engine used by nodejs in the Starter.ejs file.

    Starter.ejs file:-
    	< html ng-app="main">
    	< head>
    	< meta charset="utf-8" />
    	< meta name="viewport" content="width=device-width, initial-scale=1.0">
    	< meta name="viewport" content="width=device-width" />
    	< title>Super Application< /title>
    	< link href="bootstrap.css" rel="stylesheet" />
    	< link href="Site.css" rel="stylesheet" />
    	< scriptsrc="modernizr-2.6.2.js">< /script>
    	< scriptsrc="jquery-1.10.2.js">< /script>
    	< script src="bootstrap.js">< /script>
    	< script src="angular.js">< /script>
    	< script src="angular-route.js">< /script>
    	< script src="angular-ui-router.js">< /script>
    	< script src="angular-resource.js">< /script>
    	< scriptsrc="/Modules/mainApp.js">< /script>
    	< scriptsrc="/Controllers/MainController.js">< /script>
    	< scriptsrc="/Controllers/AuthController.js">< /script>
    	< /head>
    	< body>
    	< div class="navbarnavbar-inverse navbar-fixed-top">
    	< div class="container">
    	< div class="navbar-header">
    	< button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
    	< span class="icon-bar">< /span>
    	< span class="icon-bar">< /span>
    	< span class="icon-bar">< /span>
    	< /button>
    	< a class="navbar-brand" href="#/home">Application name< /a>
    	< /div>
    
    	< div class="navbar-collapse collapse">
    	< ul class="navnavbar-nav">
    	< li>< a href="#/home">Home< /a>< /li>
    	< li>< a href="#/about">About< /a>< /li>
    	< li>< a href="#/contact">Contact< /a>< /li>
    	< /ul>
    	< div class="container">
    	< div class="navbar-header">
    	< button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
    	< span class="icon-bar">< /span>
    	< span class="icon-bar">< /span>
    	< span class="icon-bar">< /span>
    	< /button>
    	< a class="navbar-brand" href="#/home">Application name< /a>
    	< /div>
    
    	< div class="navbar-collapse collapse">
    	< ul class="navnavbar-nav">
    	< li>< a href="#/home">Home< /a>< /li>
    	< li>< a href="#/about">About< /a>< /li>
    	< li>< a href="#/contact">Contact< /a>< /li>
    	< /ul>
    	< ul class="navnavbar-navnavbar-right">
    	< li>< p class="navbar-right navbar-text">Signed in as {{current_user}}< /p>< /li>
    	< li>< p class="navbar-right navbar-text" ng-hide="authenticated">
    	< a href="#/login">Login< /a> or < a href="#/register">Register< /a>
    	< /p>< /li>
    	< li>< p class="navbar-right navbar-text" ng-show="authenticated">
    	< a href="#" ng-click="signout()">Logout< /a>
    	< /p>< /li>
    	< div class="container">
    	< div class="navbar-header">
    	< button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
    	< span class="icon-bar">< /span>
    	< span class="icon-bar">< /span>
    	< span class="icon-bar">< /span>
    	< /button>
    	< a class="navbar-brand" href="#/home">Application name< /a>
    	< /div>
    
    	< div class="navbar-collapse collapse">
    	< ul class="navnavbar-nav">
    	< li>< a href="#/home">Home< /a>< /li>
    	< li>< a href="#/about">About< /a>< /li>
    	< li>< a href="#/contact">Contact< /a>< /li>
    	< /ul>
    	< ul class="navnavbar-navnavbar-right">
    	< li>< p class="navbar-right navbar-text">Signed in as {{current_user}}< /p>< /li>
    	< li>< p class="navbar-right navbar-text" ng-hide="authenticated">
    	< a href="#/login">Login< /a> or < a href="#/register">Register< /a>
    	< /p>< /li>
    	< li>< p class="navbar-right navbar-text" ng-show="authenticated">
    	< a href="#" ng-click="signout()">Logout< /a>
    	< /p>< /li>
    	< div class="container">
    	< div class="navbar-header">
    	< button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
    	< span class="icon-bar">< /span>
    	< span class="icon-bar">< /span>
    	< span class="icon-bar">< /span>
    	< /button>
    	< a class="navbar-brand" href="#/home">Application name< /a>
    	< /div>
    
    	< div class="navbar-collapse collapse">
    	< ul class="navnavbar-nav">
    	< li>< a href="#/home">Home< /a>< /li>
    	< li>< a href="#/about">About< /a>< /li>
    	< li>< a href="#/contact">Contact< /a>< /li>
    	< /ul>
    	< ul class="navnavbar-navnavbar-right">
    	< li>< p class="navbar-right navbar-text">Signed in as {{current_user}}< /p>< /li>
    	< li>< p class="navbar-right navbar-text" ng-hide="authenticated">
    	< a href="#/login">Login< /a> or < a href="#/register">Register< /a>
    	< /p>< /li>
    	< li>< p class="navbar-right navbar-text" ng-show="authenticated">
    	< a href="#" ng-click="signout()">Logout< /a>
    	< /p>< /li>
    	< div class="container">
    	< div class="navbar-header">
    	< button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
    	< span class="icon-bar">< /span>
    	< span class="icon-bar">< /span>
    	< span class="icon-bar">< /span>
    	< /button>
    	< a class="navbar-brand" href="#/home">Application name< /a>
    	< /div>
    
    	< div class="navbar-collapse collapse">
    	< ul class="navnavbar-nav">
    	< li>< a href="#/home">Home< /a>< /li>
    	< li>< a href="#/about">About< /a>< /li>
    	< li>< a href="#/contact">Contact< /a>< /li>
    	< /ul>
    	< ul class="navnavbar-navnavbar-right">
    	< li>< p class="navbar-right navbar-text">Signed in as {{current_user}}< /p>< /li>
    	< li>< p class="navbar-right navbar-text" ng-hide="authenticated">
    	< a href="#/login">Login< /a> or < a href="#/register">Register< /a>
    	< /p>< /li>
    	< li>< p class="navbar-right navbar-text" ng-show="authenticated">
    	< a href="#" ng-click="signout()">Logout< /a>
    	< /p>< /li>
    
    	< div class="container">
    	< div class="navbar-header">
    	< button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
    	< span class="icon-bar">< /span>
    	< span class="icon-bar">< /span>
    	< span class="icon-bar">< /span>
    	< /button>
    	< a class="navbar-brand" href="#/home">Application name< /a>
    	< /div>
    
    	< div class="navbar-collapse collapse">
    	< ul class="navnavbar-nav">
    	< li>< a href="#/home">Home< /a>< /li>
    	< li>< a href="#/about">About< /a>< /li>
    	< li>< a href="#/contact">Contact< /a>< /li>
    	< /ul>
    	< ul class="navnavbar-navnavbar-right">
    	< li>< p class="navbar-right navbar-text">Signed in as {{current_user}}< /p>< /li>
    	< li>< p class="navbar-right navbar-text" ng-hide="authenticated">
    	< a href="#/login">Login< /a> or < a href="#/register">Register< /a>
    	< /p>< /li>
    	< li>< p class="navbar-right navbar-text" ng-show="authenticated">
    	< a href="#" ng-click="signout()">Logout< /a>
    	< /p>< /li>
    	< div class="container">
    	< div class="navbar-header">
    	< button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
    	< span class="icon-bar">< /span>
    	< span class="icon-bar">< /span>
    	< span class="icon-bar">< /span>
    	< /button>
    	< a class="navbar-brand" href="#/home">Application name< /a>
    	< /div>
    
    	< div class="navbar-collapse collapse">
    	< ul class="navnavbar-nav">
    	< li>< a href="#/home">Home< /a>< /li>
    	< li>< a href="#/about">About< /a>< /li>
    	< li>< a href="#/contact">Contact< /a>< /li>
    	< /ul>
    	< ul class="navnavbar-navnavbar-right">
    	< li>< p class="navbar-right navbar-text">Signed in as {{current_user}}< /p>< /li>
    	< li>< p class="navbar-right navbar-text" ng-hide="authenticated">
    	< a href="#/login">Login< /a> or < a href="#/register">Register< /a>
    	< /p>< /li>
    	< li>< p class="navbar-right navbar-text" ng-show="authenticated">
    	< a href="#" ng-click="signout()">Logout< /a>
    	< /p>< /li>
    	< ul class="navnavbar-navnavbar-right">
    	< li>< p class="navbar-right navbar-text">Signed in as {{current_user}}< /p>< /li>
    	< li>< p class="navbar-right navbar-text" ng-hide="authenticated">
    	< a href="#/login">Login< /a> or < a href="#/register">Register< /a>
    	< /p>< /li>
    	< li>< p class="navbar-right navbar-text" ng-show="authenticated">
    	< a href="#" ng-click="signout()">Logout< /a>
    	< /p>< /li>
    	< /ul>
    	< /div>
    	< /div>
    	< /div>
    	< div class="container body-content">
    	< divui-view>
    	< /div>
    	< hr />
    	< footer>
    	< p>My ASP.NET Application< /p>
    	< /footer>
    	< /div>
    	< /body>
    	< /html>
    	

    We’ve finally got a completely working boilerplate app. It uses social network login as well as authentication. We won’t go into great detail about it, but we will make our own app. The public folder includes our AngularJS front end, while the server folder contains our NodeJS backend, as you can see from the application structure.

    There is another technique to duplicate a post in order to avoid undesired post modification in any component that retrieves our post. We’ll take an event-driven strategy, in which we actively push information to the components about new postings being accessible. We may use the event emitter for this, but it has be used in combination with the @output decorator. Instead, we’ll make advantage of a feature offered by the Rxjs package called Subject.

    The Rxjs is all about observables, which is a more difficult idea to comprehend. This package is all about objects and allows us to transmit data between them. This functionality is a fundamental requirement, not a part of Angular.

    Create a new route in the Routes folder called authentication.js from authentication requests.

    authentication.js File:-
    	var express = require('express');
    	var router = express.Router();
    	module.exports = function(passport){
    	//sends successful login state back to view(angular)
    	router.get('/success',function(req,res){
    	res.send({state: 'success', user: req.user ? req.user: null});    
    	    });
    	//send failure login state back to view(angular)
    	router.get('/failure',function(req,res){
    	res.send({state: 'failure',user:null,message:"Invalid username or password"});
    	    });
    
    	var mongoose = require('mongoose');   
    	var User = mongoose.model('User');
    	varLocalStrategy   = require('passport-local').Strategy;
    	varbCrypt = require('bcrypt-nodejs');
    	module.exports = function(passport){
    	// Passport needs to be able to serialize and deserialize users to support persistent login sessions
    	    passport.serializeUser(function(user, done) {
    	        console.log('serializing user:',user.username);
    	        done(null, user._id);
    	    });
    	passport.deserializeUser(function(id, done) {
    	        User.findById(id, function(err, user) {
    	            console.log('deserializing user:',user.username);
    	            done(err, user);
    	        });
    	    });
    	passport.use('login', new LocalStrategy({
    	            passReqToCallback : true
    	        },
    	        function(req, username, password, done) { 
    	        // check in mongo if a user with username exists or not
    	            User.findOne({ 'username' :  username }, 
    	                function(err, user) {
    	                    // In case of any error, return using the done method
    	                    if (err)
    	                        return done(err);
    	                    // Username does not exist, log the error and redirect back
    	                    if (!user){
    	                        console.log('User Not Found with username '+username);
    	                        return done(null, false);                 
    	                    }
    	                    // User exists but wrong password, log the error 
    	                    if (!isValidPassword(user, password)){
    	                        console.log('Invalid Password');
    	                        return done(null, false); // redirect back to login page
    	                    }
    	                    // User and password both match, return user from done method
    	                    // which will be treated like success
    	                    return done(null, user);
    	                }
    	            );
    	        }
    	    ));
    	passport.use('signup', new LocalStrategy({
    	            passReqToCallback : true // allows us to pass back the entire request to the callback
    	        },
    	        function(req, username, password, done, email, role) {
    	// find a user in mongo with provided username
    	            User.findOne({ 'username' :  username }, function(err, user) {
    	                // In case of any error, return using the done method
    	                if (err){
    	                    console.log('Error in SignUp: '+ err);
    	                    return done(err);
    	                }
    	                // already exists
    	                if (user) {
    	                    console.log('User already exists with username: '+username);
    	                    return done(null, false);
    	                } else {
    	                    // if there is no user, create the user
    	                    varnewUser = new User();
    	                    // set the user's local credentials
    	                    newUser.username = username;
    	                    newUser.password = createHash(password);
    	                    newUser.email = req.body.email;
    	                    newUser.role = req.body.role;
    	                    // save the user
    	                    newUser.save(function(err) {
    	                        if (err){
    	                            console.log('Error in Saving user: '+err);  
    	                            throw err;  
    	                        }
    	                        console.log(newUser.username + ' Registration succesful');    
    	                        return done(null, newUser);
    	                    });
    	                }
    	            });
    	        })
    	    );
    	varisValidPassword = function(user, password){
    	        returnbCrypt.compareSync(password, user.password);
    	    };
    	    // Generates hash using bCrypt
    	    varcreateHash = function(password){
    	        returnbCrypt.hashSync(password, bCrypt.genSaltSync(10), null);
    	    };
    	};
    	var mongoose = require('mongoose');   
    	var User = mongoose.model('User');
    	varLocalStrategy   = require('passport-local').Strategy;
    	varbCrypt = require('bcrypt-nodejs');
    	module.exports = function(passport){
    	// Passport needs to be able to serialize and deserialize users to support persistent login sessions
    	    passport.serializeUser(function(user, done) {
    	        console.log('serializing user:',user.username);
    	        done(null, user._id);
    	    });
    	passport.deserializeUser(function(id, done) {
    	        User.findById(id, function(err, user) {
    	            console.log('deserializing user:',user.username);
    	            done(err, user);
    	        });
    	    });
    	passport.use('login', new LocalStrategy({
    	            passReqToCallback : true
    	        },
    	        function(req, username, password, done) { 
    	        // check in mongo if a user with username exists or not
    	            User.findOne({ 'username' :  username }, 
    	                function(err, user) {
    	                    // In case of any error, return using the done method
    	                    if (err)
    	                        return done(err);
    	                    // Username does not exist, log the error and redirect back
    	                    if (!user){
    	                        console.log('User Not Found with username '+username);
    	                        return done(null, false);                 
    	                    }
    	                    // User exists but wrong password, log the error 
    	                    if (!isValidPassword(user, password)){
    	                        console.log('Invalid Password');
    	                        return done(null, false); // redirect back to login page
    	                    }
    	                    // User and password both match, return user from done method
    	                    // which will be treated like success
    	                    return done(null, user);
    	                }
    	            );
    	        }
    	    ));
    	passport.use('signup', new LocalStrategy({
    	            passReqToCallback : true // allows us to pass back the entire request to the callback
    	        },
    	        function(req, username, password, done, email, role) {
    	// find a user in mongo with provided username
    	            User.findOne({ 'username' :  username }, function(err, user) {
    	                // In case of any error, return using the done method
    	                if (err){
    	                    console.log('Error in SignUp: '+ err);
    	                    return done(err);
    	                }
    	                // already exists
    	                if (user) {
    	                    console.log('User already exists with username: '+username);
    	                    return done(null, false);
    	                } else {
    	                    // if there is no user, create the user
    	                    varnewUser = new User();
    	                    // set the user's local credentials
    	                    newUser.username = username;
    	                    newUser.password = createHash(password);
    	                    newUser.email = req.body.email;
    	                    newUser.role = req.body.role;
    	                    // save the user
    	                    newUser.save(function(err) {
    	                        if (err){
    	                            console.log('Error in Saving user: '+err);  
    	                            throw err;  
    	                        }
    	                        console.log(newUser.username + ' Registration succesful');    
    	                        return done(null, newUser);
    	                    });
    	                }
    	            });
    	        })
    	    );
    	varisValidPassword = function(user, password){
    	        returnbCrypt.compareSync(password, user.password);
    	    };
    	    // Generates hash using bCrypt
    	    varcreateHash = function(password){
    	        returnbCrypt.hashSync(password, bCrypt.genSaltSync(10), null);
    	    };
    	};
    	    //login requeset
    	router.post('/login',passport.authenticate('login',{
    	successRedirect: '/auth/success',
    	failureRedirect: '/auth/failure'
    	    }));
    	//signup request
    	router.post('/signup', passport.authenticate('signup', {
    	successRedirect: '/auth/success',
    	failureRedirect: '/auth/failure'
    	    }));
    	//logout request
    	router.get('/signout', function(req, res) {
    	req.session.user = null;
    	req.logout();
    	res.redirect('/');
    	    });
    	return router;
    	}
    	

    We must first install the different MEAN software packages before we can begin. Begin by downloading Node.js from the official website. After that, you must download and install MongoDB. Installing MongoDB on a number of operating systems is covered on the install MongoDB page. We’ll start with a MEAN boilerplate project to make things simpler. Simply clone the boilerplate repo and use npm to install the dependencies, as demonstrated in the Server.js file below.

    Server.js File:-
    	//server.js
    	//adding opensource modules to application 
    	var express = require('express'); //express 
    	var path = require('path'); //for refering physical files here
    	var logger = require('morgan'); 
    	varcookieParser = require('cookie-parser'); //for maintain sessions
    	varbodyParser = require('body-parser'); //for parsing json
    	varbcrypt = require('bcrypt-nodejs'); 
    	var passport = require('passport'); //Using passportjs for authentication
    	varLocalStrategy = require('passport-local').Strategy; //using passport strategy
    	var session = require('express-session'); //for maintaining sessions
    	var mongoose = require('mongoose'); //for mongodb, database
    	varmodels_user = require('./Angular/Models/user.js'); // refering models in server.js
    
    	//connection database
    	mongoose.connect('mongodb://localhost/AngularizeApp');
    
    	//import the routers
    	var router = require('./Routes/router');
    	var authenticate = require('./Routes/authentication')(passport);
    
    	//for using express throughout this application
    	var app = express();
    
    	//tell node that My application will use ejs engine for rendering, view engine setup
    	app.set('views', path.join(__dirname, 'Views'));
    	app.set('view engine', 'ejs');
    
    	//tell node the global configuration about parser,logger and passport
    	app.use(cookieParser());
    	app.use(logger('dev'));
    	app.use(session({
    	secret: 'keyboard cat'
    	}));
    	app.use(bodyParser.json());
    	app.use(bodyParser.urlencoded({ extended: false }));
    	app.use(passport.initialize()); //initializing passport
    	app.use(passport.session()); //initializing passport session
    
    	//tell node about these directories that application may get resources from
    	app.use('/', router);
    	app.use('/auth', authenticate);
    	app.use(express.static(path.join(__dirname, 'scripts')));
    	app.use(express.static(path.join(__dirname, 'Content')));
    	app.use(express.static(path.join(__dirname, 'Angular')));
    	app.use(express.static(path.join(__dirname, 'Views/Main')));
    	app.use(express.static(path.join(__dirname, 'Views/Authentication')));
    	//tell node that My application will use ejs engine for rendering, view engine setup
    	app.set('views', path.join(__dirname, 'Views'));
    	app.set('view engine', 'ejs');
    
    	//tell node the global configuration about parser,logger and passport
    	app.use(cookieParser());
    	app.use(logger('dev'));
    	app.use(session({
    	secret: 'keyboard cat'
    	}));
    	app.use(bodyParser.json());
    	app.use(bodyParser.urlencoded({ extended: false }));
    	app.use(passport.initialize()); //initializing passport
    	app.use(passport.session()); //initializing passport session
    
    	//tell node about these directories that application may get resources from
    	app.use('/', router);
    	app.use('/auth', authenticate);
    	app.use(express.static(path.join(__dirname, 'scripts')));
    	app.use(express.static(path.join(__dirname, 'Content')));
    	app.use(express.static(path.join(__dirname, 'Angular')));
    	app.use(express.static(path.join(__dirname, 'Views/Main')));
    	app.use(express.static(path.join(__dirname, 'Views/Authentication')));
    	//tell node that My application will use ejs engine for rendering, view engine setup
    	app.set('views', path.join(__dirname, 'Views'));
    	app.set('view engine', 'ejs');
    
    	//tell node the global configuration about parser,logger and passport
    	app.use(cookieParser());
    	app.use(logger('dev'));
    	app.use(session({
    	secret: 'keyboard cat'
    	}));
    	app.use(bodyParser.json());
    	app.use(bodyParser.urlencoded({ extended: false }));
    	app.use(passport.initialize()); //initializing passport
    	app.use(passport.session()); //initializing passport session
    
    	//tell node about these directories that application may get resources from
    	app.use('/', router);
    	app.use('/auth', authenticate);
    	app.use(express.static(path.join(__dirname, 'scripts')));
    	app.use(express.static(path.join(__dirname, 'Content')));
    	app.use(express.static(path.join(__dirname, 'Angular')));
    	app.use(express.static(path.join(__dirname, 'Views/Main')));
    	app.use(express.static(path.join(__dirname, 'Views/Authentication')));
    	//tell node that My application will use ejs engine for rendering, view engine setup
    	app.set('views', path.join(__dirname, 'Views'));
    	app.set('view engine', 'ejs');
    
    	//tell node the global configuration about parser,logger and passport
    	app.use(cookieParser());
    	app.use(logger('dev'));
    	app.use(session({
    	secret: 'keyboard cat'
    	}));
    	app.use(bodyParser.json());
    	app.use(bodyParser.urlencoded({ extended: false }));
    	app.use(passport.initialize()); //initializing passport
    	app.use(passport.session()); //initializing passport session
    
    	//tell node about these directories that application may get resources from
    	app.use('/', router);
    	app.use('/auth', authenticate);
    	app.use(express.static(path.join(__dirname, 'scripts')));
    	app.use(express.static(path.join(__dirname, 'Content')));
    	app.use(logger('dev'));
    	app.use(session({
    	secret: 'keyboard cat'
    	}));
    	app.use(bodyParser.json());
    	app.use(bodyParser.urlencoded({ extended: false }));
    	app.use(passport.initialize()); //initializing passport
    	app.use(passport.session()); //initializing passport session
    
    	//tell node about these directories that application may get resources from
    	app.use('/', router);
    	app.use('/auth', authenticate);
    	app.use(express.static(path.join(__dirname, 'scripts')));
    	app.use(express.static(path.join(__dirname, 'Content')));
    	app.use(express.static(path.join(__dirname, 'Angular')));
    	app.use(express.static(path.join(__dirname, 'Views/Main')));
    	app.use(express.static(path.join(__dirname, 'Views/Authentication')));
    
    	//providing auth-api to passport so that it can use it.
    	varinitPassport = require('./Passport/passport-init');
    	initPassport(passport);
    	app.use(logger('dev'));
    	app.use(session({
    	secret: 'keyboard cat'
    	}));
    	app.use(bodyParser.json());
    	app.use(bodyParser.urlencoded({ extended: false }));
    	app.use(passport.initialize()); //initializing passport
    	app.use(passport.session()); //initializing passport session
    
    	//tell node about these directories that application may get resources from
    	app.use('/', router);
    	app.use('/auth', authenticate);
    	app.use(express.static(path.join(__dirname, 'scripts')));
    	app.use(express.static(path.join(__dirname, 'Content')));
    	app.use(express.static(path.join(__dirname, 'Angular')));
    	app.use(express.static(path.join(__dirname, 'Views/Main')));
    	app.use(express.static(path.join(__dirname, 'Views/Authentication')));
    
    	//providing auth-api to passport so that it can use it.
    	varinitPassport = require('./Passport/passport-init');
    	initPassport(passport);
    	app.use(express.static(path.join(__dirname, 'Angular')));
    	app.use(express.static(path.join(__dirname, 'Views/Main')));
    	app.use(express.static(path.join(__dirname, 'Views/Authentication')));
    
    	//providing auth-api to passport so that it can use it.
    	varinitPassport = require('./Passport/passport-init');
    	initPassport(passport);
    	//running server on node
    	var server = app.listen(3000, function () {
    	var host = server.address().address;
    	var port = server.address().port;
    	console.log('Example app listening at http://%s:%s', host, port);
    	});
    	//exporting this application as a module
    	module.exports = app;
    	}};
    	

    A subscription is created using the subscribe() method. The subscribe function takes three arguments: the first is a function that is called whenever new data is emitted, the second argument is a function that is called whenever an error is emitted, and the third argument is a function that is called when the observable is finished, or there are no more values to be expected. As a result, we’ll just pass the first argument because the second isn’t required.

    Output

    Copyright 1999- Ducat Creative, All rights reserved.