Quick Contact


    Service in MEAN Stack

    We learnt about forms and how to utilise them in our application in the previous part. We’ll learn how to get new posts from the post-create component to the post-list component in this section.

    • We’ve created a property and event binding chain.
    • We used the post-create component to send our message.
    • This message was forwarded to its parent component.
    • We sent it to the post-list component from the parent component.

    This works perfectly. However, in a larger application, it becomes increasingly common. Because we have longer chains of property and event binding to get an element from component X to Y, Y to Z, and so on, this is the case.

    We’ll call our new file service.ts and save it in the posts folder. This file will be produced in the same manner as the post.model.ts file.

    We will construct a service class that is a typescript class in this file. We utilise the export keyword to build this class since we use it in a variety of components. We need to add a list of posts to this class, therefore we’ll make a posts array of type Post as follows:

    	require('./api/models/db');
    
    	constcookieParser = require('cookie-parser');
    	constcreateError = require('http-errors');
    	const express = require('express');
    	const logger = require('morgan');
    	const path = require('path');
    	constroutesApi = require('./api/routes/index');
    	const app = express();
    	// view engine setup
    	app.set('views', path.join(__dirname, 'views'));
    	app.set('view engine', 'pug');
    
    	app.use(logger('dev'));
    	app.use(express.json());
    	app.use(express.urlencoded({ extended: false }));
    	app.use(cookieParser());
    	app.use(express.static(path.join(Tutorials.ducatindia.com, 'public')));
    
    	app.use('/api', routesApi);
    	app.use((req, res, next) => {
    	  next(createError(404));
    	});
    	app.use((err, req, res, next) => {
    	  // set locals, only providing error in development
    	res.locals.message = err.message;
    	res.locals.error = req.app.get('env') === 'development' ? err : {};
    
    	  // render the error page
    	res.status(err.status || 500);
    	res.render('error');
    	});
    
    	module.exports = app;
    	Add the following to api/models/db.js:
    	require('./users');
    	const mongoose = require('mongoose');
    	constdbURI = 'mongodb://localhost:27017/meanAuth';
    	mongoose.set('useCreateIndex', true);
    	mongoose.connect(dbURI, {
    	useNewUrlParser: true,
    	useUnifiedTopology: true
    	});
    	mongoose.connection.on('connected', () => {
    	  console.log(`Mongoose connected to ${dbURI}`);
    	});
    	mongoose.connection.on('error', (err) => {
    	  console.log(`Mongoose connection error: ${err}`);
    	});
    	mongoose.connection.on('disconnected', () => {
    	  console.log('Mongoose disconnected');
    	});
    	Add the following to api/routes/index.js:
    	constctrlAuth = require('../controllers/authentication');
    	constctrlProfile = require('../controllers/profile');
    
    	const express = require('express');
    	const router = express.Router();
    	router.get('/profile/:userid', ctrlProfile.profileRead);
    	router.post('/register', ctrlAuth.register);
    	router.post('/login', ctrlAuth.login);
    	module.exports = router;
    	

    Because arrays and objects are reference types in JavaScript and typescript, we don’t want to return the actual array. A reference type is one that will not be duplicated if it is attempted. The thing in memory will remain unchanged. Because we just duplicated the address, the pointer now points to that object rather than the value. As a result, we’ll utilise the spread operator, which is a next-generation JavaScript feature, in the following method to make a genuine duplicate of it:

    getPosts(){

    return [PostMethod];

    }

    We used square brackets to create a new array, and the three dots to take all the elements from the posts array and put them to this new array in the preceding code.

    We also make the addPost() function, which will assist us in adding a post to the array. We may send either a post or just a title and content to this function. Following that, we’ll create a new Post post. It’s a JavaScript object with two properties: title and content. The following code defines the property and inserts the newly produced post into the posts array:

    addPost(title: string, content: string){

    const post: Post={title: title, content: content};

    this.posts.push(post);

    }

    Both of these will be used in the post-list and post-create components. With property and event binding, we can obtain and add the post without providing data. This may be accomplished by including this Service into the post-create and post-list components. Dependency injection is a feature of the Service that we employ.

    6) Next, we’ll add a function Object() { [native code] } in our post list component. When Angular creates an instance of this component, this function Object() { [native code] } will be invoked. Angular features a sophisticated dependency injection mechanism that can figure out what we want and deliver it to us. As a result, we must declare the Service as an argument in the function Object() { [native code] } as follows:

    PostService is an argument in the above code, and PostService is the type of the argument to give us an idea of what it should really provide us.

    7) We now require a property to hold the Service instance. We may either build a new property to hold the Service object or make the constructor’s postService parameter public.

    By adding a new property, you can:

    constructor(postsService: PostService) this.postsService = postsService;

    constructor(postsService: PostService) constructor(postsService: PostService)

    constructor(postsService: PostService) constructor(postsService: PostService)

    constructor(postsService

    Angular is currently unable to meet this requirement since it is unaware of the postService. This is due to the fact that it is not scanning all of our files. So, there are two methods to make angular aware:

    By modifying the app.module.ts file to include the postService. We’ll add PostService to the providers array as follows:

    providers: [], bootstrap: [AppComponent, PostService] import PostService from ‘./posts/posts.service’

    We’ll go ahead and add a @injectable parameter to the postService. Also imported from @angular/core is this injectable. We supply a JavaScript object in between the parenthesis to customise this in the following fashion.

    server.js

    	let express = require('express'),
    	   path = require('path'),
    	   mongoose = require('mongoose'),
    	cors = require('cors'),
    	bodyParser = require('body-parser'),
    	dbConfig = require('./database/db');
    
    	// Connecting with mongo db
    	mongoose.Promise = global.Promise;
    	mongoose.connect(dbConfig.db, {
    	useNewUrlParser: true
    	}).then(() => {
    	      console.log('Database sucessfully connected')
    	   },
    	   error => {
    	      console.log('Database could not connected: ' + error)
    	   }
    	)
    
    	// Setting up port with express js
    	constemployeeRoute = require('../backend/routes/employee.route')
    	const app = express();
    	app.use(bodyParser.json());
    	app.use(bodyParser.urlencoded({
    	   extended: false
    	}));
    	app.use(cors()); 
    	app.use(express.static(path.join(__dirname, 'dist/mean-stack-crud-app')));
    	app.use('/', express.static(path.join(__dirname, 'dist/mean-stack-crud-app')));
    	app.use('/api', employeeRoute)
    
    	// Create port
    	const port = process.env.PORT || 4000;
    	const server = app.listen(port, () => {
    	  console.log('Connected to port ' + port)
    	})
    	mongoose.Promise = global.Promise;
    	mongoose.connect(dbConfig.db, {
    	useNewUrlParser: true
    	}).then(() => {
    	      console.log('Database sucessfully connected')
    	   },
    	   error => {
    	      console.log('Database could not connected: ' + error)
    	   }
    	)
    
    	// Setting up port with express js
    	constemployeeRoute = require('../backend/routes/employee.route')
    	const app = express();
    	app.use(bodyParser.json());
    	app.use(bodyParser.urlencoded({
    	   extended: false
    	}));
    	mongoose.Promise = global.Promise;
    	mongoose.connect(dbConfig.db, {
    	useNewUrlParser: true
    	}).then(() => {
    	      console.log('Database sucessfully connected')
    	   },
    	   error => {
    	      console.log('Database could not connected: ' + error)
    	   }
    	)
    
    	// Setting up port with express js
    	constemployeeRoute = require('../backend/routes/employee.route')
    	const app = express();
    	app.use(bodyParser.json());
    	app.use(bodyParser.urlencoded({
    	   extended: false
    	}));
    	// Find 404 and hand over to error handler
    	app.use((req, res, next) => {
    	   next(createError(404));
    	});
    
    	app.use(function (err, req, res, next) {
    	console.error(err.message); 
    	  if (!err.statusCode) err.statusCode = 1500; e to 'Internal Server Error (500)'
    	res.status(err.statusCode).send(err.message); 
    	});
    	Using mongoose.js, add the following code to your MEAN Stack project to create RESTful APIs.
    	const express = require('express');
    	const app = express();
    	constemployeeRoute = express.Router();
    
    	let Employee = require('../models/Employee');
    
    	// Add Employee
    	employeeRoute.route('/create').post((req, res, next) => {
    	Employee.create(req.body, (error, data) => {
    	    if (error) {
    	      return next(error)
    	    } else {
    	res.json(data)
    	    }
    	  })
    	});
    
    	// Get All Employees
    	employeeRoute.route('/').get((req, res) => {
    	Employee.find((error, data) => {
    	    if (error) {
    	      return next(error)
    	    } else {
    	res.json(data)
    	    }
    	  })
    	})
    	employeeRoute.route('/update/:id').put((req, res, next) => {
    	Employee.findByIdAndUpdate(req.params.id, {
    	    $set: req.body
    	  }, (error, data) => {
    	    if (error) {
    	      return next(error);
    	      console.log(error)
    	    } else {
    	res.json(data)
    	      console.log('Data updated successfully')
    	    }
    	  })
    	})
    
    	employeeRoute.route('/delete/:id').delete((req, res, next) => {
    	Employee.findOneAndRemove(req.params.id, (error, data) => {
    	    if (error) {
    	      return next(error);
    	    } else {
    	res.status(200).json({
    	msg: data
    	      })
    	    }
    	  })
    	})
    	employeeRoute.route('/update/:id').put((req, res, next) => {
    	Employee.findByIdAndUpdate(req.params.id, {
    	    $set: req.body
    	  }, (error, data) => {
    	    if (error) {
    	      return next(error);
    	      console.log(error)
    	    } else {
    	res.json(data)
    	      console.log('Data updated successfully')
    	    }
    	  })
    	})
    
    	employeeRoute.route('/delete/:id').delete((req, res, next) => {
    	Employee.findOneAndRemove(req.params.id, (error, data) => {
    	    if (error) {
    	      return next(error);
    	    } else {
    	res.status(200).json({
    	msg: data
    	      })
    	    }
    	  })
    	})
    
    	employeeRoute.route('/read/:id').get((req, res) => {
    	Employee.findById(req.params.id, (error, data) => {
    	    if (error) {
    	      return next(error)
    	    } else {
    	res.json(data)
    	    }
    	  })
    	})
    
    	employeeRoute.route('/update/:id').put((req, res, next) => {
    	Employee.findByIdAndUpdate(req.params.id, {
    	    $set: req.body
    	  }, (error, data) => {
    	    if (error) {
    	      return next(error);
    	      console.log(error)
    	    } else {
    	res.json(data)
    	      console.log('Data updated successfully')
    	    }
    	  })
    	})
    
    	employeeRoute.route('/delete/:id').delete((req, res, next) => {
    	Employee.findOneAndRemove(req.params.id, (error, data) => {
    	    if (error) {
    	      return next(error);
    	    } else {
    	res.status(200).json({
    	msg: data
    	      })
    	    }
    	  })
    	})
    	

    MEAN is an open source web stack for building cloud-hosted apps. MEAN stack apps are scalable, extendable, and versatile, making them ideal for cloud hosting. The stack comes with its own web server, making it simple to install, and the database can be expanded on demand to handle transient use surges. A MEAN application is released into the world designed to take advantage of the cloud’s cost savings and performance enhancements.

    JavaScript has long been a popular front-end web development language because it is versatile, dynamic, and simple to use. For a few years, however, it has only been available for backend and database development, allowing developers to construct apps utilising end-to-end JavaScript. You can simplify your development teams since MEAN utilises the same language throughout. MEAN eliminates the need to employ many professionals to create distinct parts of an app. Instead, you may employ a single pool of JavaScript developers to work on demand, wherever and whenever they are needed. Standardizing on JavaScript also allows you to reuse code throughout the whole application, decreasing the amount of time you spend reinventing the wheel.

    Creating the MongoDB Data Schema with Mongoose

    Then, under api/models/users.js, create a schema. It specifies that an email address, a name, a hash, and a salt are all required. Instead of keeping a password, the hash and salt will be utilised. We’ll use the email as the login credentials, therefore it’s set to unique. Here’s how it works:

    	const mongoose = require('mongoose');
    
    	constuserSchema = new mongoose.Schema({
    	  email: {
    	    type: String,
    	    unique: true,
    	    required: true
    	  },
    	contact: {
    	    type: String,
    	    unique: true,
    	    required: true
    	  },
    	  first name: {
    	    type: String,
    	    required: true
    	  },
    	  hash: String,
    	  salt: String
    	  name: {
    	    type: String,
    	    required: true
    	  },
    	  hash: String,
    	  salt: String
    	});
    	mongoose.model('User', userSchema);
    	
    server.js

    As we said in our “package.json” file, the “server.js” file is the application’s entry point. Place the “server.js” file in the application’s root directory and put the following code into it.

    	var express=require('express');    
    	var path=require('path');    
    	varbodyParser=require('body-parser');    
    
    	// In the above three lines, we import the required packages     
    
    	var index=require('./routes/index');    
    	varapi=require('./routes/api');    
    
    	// index and API object contains the path of routing files for our application    
    
    	var port=4500;    
    	var app=express();    
    
    	//Define the port and create an object of the express class    
    
    	app.set('view engine','ejs');    
    	app.set('views',path.join(__dirname,'/client/views'));    
    
    	// define the view engine and set the path for views files    
    
    	app.engine('html',require('ejs').renderFile);    
    	//Register given template engine callbac function as extension    
    
    	app.use(express.static(path.join(__dirname,'/client')));    
    
    	// Define the path for the static files like image, css and js files    
    
    	app.use(bodyParser.json());    
    	app.use(bodyParser.urlencoded({extended:false}));    
    	db.employees.insert([{  
    	  "EmployeeName": "AnkurVerma",  
    	  "Designation": "Mobile Developer",  
    	  "Project": "OUP",  
    	  "Skills": "Java, Android Studio, Xamarin"  
    	 }, {  
    	  "EmployeeName": "Dheeraj Sharma",  
    	  "Designation": " Developer",  
    	  "Project": "Lion Servcies",  
    	  "Skills": "C#,Asp.Net,MVC,AngularJS"  
    	 },  
    	 {  
    	  "EmployeeName": "Dhramveer",  
    	  "Designation": " Developer",  
    	  "Project": "VMesh",  
    	  "Skills": "C#,Asp.Net,MVC,AngularJS"  
    	 },  
    	 {  
    	  "EmployeeName": "Prakash",  
    	  "Designation": " Web Developer",  
    	  "Project": "OUP",  
    	  "Skills": "C#,Asp.Net,MVC,AngularJS"  
    	 },  
    	 {  
    	  "EmployeeName": "Raj Kumar",  
    	  "Designation": "Developer",  
    	  "Project": "CNS",  
    	  "Skills": "C#,Asp.Net,MVC"  
    	 }  
    	])    
    
    	app.use('/',index);    
    	app.use('/api',api);    
    	app.use('*',index);    
    	// define the middleware for routing    
    
    	app.listen(port,function(){    
    	    console.log('Server Started At '+port);    
    	})  
    	

    Copyright 1999- Ducat Creative, All rights reserved.