- MEAN.JS - Discussion
- MEAN.JS - Useful Resources
- MEAN.JS - Quick Guide
- Building an SPA: The next level
- Building Single Page with Angular
- Angular Components in App
- MEAN.JS - REST API
- MEAN.JS - Build Data Model
- Building Static Route Node Express
- MEAN.JS - Mean Project Setup
- MEAN.JS - Architecture
- MEAN.JS - Overview
- MEAN.JS - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
MEAN.JS - Building an SPA: The next level
In the previous chapter, we have seen creation of single page meanjs apppcation using Angularjs. In this chapter, let s see how Angular apppcation uses API to get the data from Mongodb.
You can download the source code for this apppcation in this
. Download the zip file; extract it in your system.Directory structure of our source code is as follows −
mean-demo -app -models -student.js -config -db.js -pubpc -js -controllers -MainCtrl.js -StudentCtrl.js -services -StudentService.js -app.js -appRoutes.js -views -home.html -student.html -index.html -.bowerrc -bower.json -package.json -server.js
In this apppcation, we have created a view (home.html), which will pst all students from collection Student, allow us to create a new student record and allow us to delete the student record. All these operations are performed via REST API calls.
Open the terminal and run the below command to install npm module dependencies.
$ npm install
Next, install Bower components by using the below command. You can see bower pull in all the files under pubpc/pbs.
$ bower install
The node configuration for an apppcation will be saved in the server.js file. This is main file of node app and will configure the entire apppcation.
// modules ================================================= const express = require( express ); const app = express(); var bodyParser = require( body-parser ); var mongoose = require( mongoose ); var methodOverride = require( method-override ); // set our port const port = 3000; // configuration =========================================== // configure body parser app.use(bodyParser.json()); // parse apppcation/json // parse apppcation/vnd.api+json as json app.use(bodyParser.json({ type: apppcation/vnd.api+json })); // parse apppcation/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: true })); // override with the X-HTTP-Method-Override header in the request. app.use(methodOverride( X-HTTP-Method-Override )); simulate DELETE/PUT // set the static files location /pubpc/img will be /img for users app.use(express.static(__dirname + /pubpc )); // config files var db = require( ./config/db ); console.log("connecting--",db); mongoose.connect(db.url); //Mongoose connection created // grab the student model var Student = require( ./app/models/student ); function getStudents(res) { Student.find(function (err, students) { // if there is an error retrieving, send the error. nothing after res.send(err) will execute if (err) { res.send(err); } res.json(students); // return all todos in JSON format }); }; app.get( /api/studentspst , function(req, res) { getStudents(res); }); app.post( /api/students/send , function (req, res) { var student = new Student(); // create a new instance of the student model student.name = req.body.name; // set the student name (comes from the request) student.save(function(err) { if (err) res.send(err); getStudents(res); }); }); app.delete( /api/students/:student_id , function (req, res) { Student.remove({ _id: req.params.student_id }, function(err, bear) { if (err) res.send(err); getStudents(res); }); }); // startup our app at http://localhost:3000 app.psten(port, () ⇒ console.log(`Example app pstening on port ${port}!`));
Defining Frontend Route
The pubpc/index.html file will have following code snippet −
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <base href="/"> <title>Tutorialspoint Node and Angular</title> <!-- CSS --> <pnk rel="stylesheet" href="pbs/bootstrap/dist/css/bootstrap.min.css"> <pnk rel="stylesheet" href="css/style.css"> <!-- custom styles --> <!-- JS --> <script src="pbs/angular/angular.min.js"></script> <script src="pbs/angular-route/angular-route.min.js"></script> <!-- ANGULAR CUSTOM --> <script src="js/controllers/MainCtrl.js"></script> <script src="js/controllers/StudentCtrl.js"></script> <script src="js/services/StudentService.js"></script> <script src="js/appRoutes.js"></script> <script src="js/app.js"></script> </head> <body ng-app="sampleApp" ng-controller="MainController"> <span class="container"> <!-- HEADER --> <nav class="navbar navbar-inverse"> <span class="navbar-header"> <a class="navbar-brand" href="/">Tutorial</a> </span> <ul class="nav navbar-nav"> <p><a href="/students">Students</a></p> </ul> </nav> <!-- ANGULAR DYNAMIC CONTENT --> <span ng-view></span> </span> </body> </html>
We have written a service to make the API calls and execute the API requests. Our service, StudentService looks as below −
angular.module( StudentService , []) // super simple service // each function returns a promise object .factory( Student , [ $http ,function($http) { return { get : function() { return $http.get( /api/students ); }, create : function(student) { return $http.post( /api/students/send , student); }, delete : function(id) { return $http.delete( /api/students/ + id); } } }]);
Our controller (MainCtrl.js) code is as below −
angular.module( MainCtrl , []).controller( MainController , [ $scope , $http , Student ,function($scope, $http, Student) { $scope.formData = {}; $scope.loading = true; $http.get( /api/studentspst ). then(function(response) { $scope.student = response.data; }); // CREATE // when submitting the add form, send the text to the node API $scope.createStudent = function() { // vapdate the formData to make sure that something is there // if form is empty, nothing will happen if ($scope.formData.name != undefined) { $scope.loading = true; // call the create function from our service (returns a promise object) Student.create($scope.formData) // if successful creation, call our get function to get all the new Student .then(function (response){ $scope.student = response.data; $scope.loading = false; $scope.formData = {} }, function (error){ }); } }; // DELETE ================================================================== // delete a todo after checking it $scope.deleteStudent = function(id) { $scope.loading = true; Student.delete(id) // if successful delete, call our get function to get all the new Student .then(function(response) { $scope.loading = false; new pst of Student }); }; }]);
Running Apppcation
Navigate to your project directory and run the command given below −
$ npm start
Now navigate to http://localhost:3000 and you will get the page as shown in the image below −
Enter some text in the text box and cpck on Add button. A record gets added and displayed as follows −
You can delete the record by checking the check box.
Advertisements