Create Database
Create new MongoDB database named learn_angular_5. This database have 1 collection: Product collection
/* Create learn_angular_5 database */
use learn_angular_5
/* Create Product collection */
db.createCollection('product');
/* Dumping data for `product` collection */
/* 1 */
{
"_id" : ObjectId("59eb397591876fae6628f17d"),
"name" : "Mobile 1",
"price" : 2.0,
"quantity" : 4.0,
"status" : true
}
/* 2 */
{
"_id" : ObjectId("59eb3a3991876fae6628f17e"),
"name" : "Mobile 2",
"price" : 5.0,
"quantity" : 2.0,
"status" : false
}
/* 3 */
{
"_id" : ObjectId("5a73bcda0f628d50d9dfe0a9"),
"name" : "Laptop 2",
"price" : 9,
"quantity" : 3,
"status" : true
}
/* 4 */
{
"_id" : ObjectId("5a73bd120f628d50d9dfe0c6"),
"name" : "Computer 1",
"price" : 15,
"quantity" : 8,
"status" : false
}
/* 5 */
{
"_id" : ObjectId("5a73e2f3ca031628a0701926"),
"name" : "Computer 2",
"price" : 20,
"quantity" : 8,
"status" : true
}
Create Server Project
Create LearnAngular5withRealApps_Server folder and select to this folder in Visual Studio Code
Install Mongoose
Use the following command to install Mongoose:
npm install mongoose --save
Install Express.JS
Use the following command to install Express.JS:
npm install express --save
npm install body-parser --save
npm install cookie-parser --save
npm install multer --save
Define Schema
Create schemas folder in Node project. Create product.schema.js file into schemas folder. Declare schema for product collection as below:
var mongoose = require('mongoose');
var ProductSchema = new mongoose.Schema(
{
name: String,
price: Number,
quantity: Number,
status: Boolean
},
{
versionKey: false
}
);
module.exports = mongoose.model('Product', ProductSchema, 'product');
Create Rest API
Create a new folder named api inside the server project. Create product.api.js file inside api folder contains Rest APIs insert new data from client
var mongoose = require('mongoose');
var Product = require('../schemas/product.schema');
var ProductAPI = {
create: function (request, response) {
var newProduct = new Product({
name: request.body.name,
price: request.body.price,
quantity: request.body.quantity,
status: request.body.status
});
newProduct.save(function (error) {
if (error) {
throw error;
}
else {
response.status(200).json(newProduct);
}
});
}
};
module.exports = ProductAPI;
Create Rest API Routing
Inside the api folder create a new file named index.js. This file will hold all the routes needed for rest api in server.
var express = require('express');
var mongoose = require('mongoose');
var router = express.Router();
mongoose.connect('mongodb://localhost:27017/learn_angular_5');
var ProductAPI = require('./product.api');
router.post('/product/create', ProductAPI.create);
module.exports = router;
Create Rest API Server
At the root of server project, create a file named server.js. This will be the entry point into node application. This will start the server and listen on a local port
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.all('/*', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key');
if (req.method == 'OPTIONS') {
res.status(200).end();
} else {
next();
}
});
app.use('/api', require('./api/index'));
var server = app.listen(9090, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Server listening at http://%s:%s", host, port)
});
Structure of Server Project
Run Rest API Server
At the root of server project run command: node server.js
Create Client Project
Create new folder named learnangular5withrealapps and select to this folder in Visual Studio Code
Install Angular 6
Open Terminal windows in Visual Studio Code and type: npm install -g @angular/cli to install Angular 6
Structure of Project
Create Entity
Create new folder, named entities in src\app folder. In this folder, create new TypeScript file, named product.entity.ts contain product information as below:
export class Product {
_id: string;
name: string;
price: number;
quantity: number;
status: boolean;
}
Create Service
Create new folder, named services in src\app folder. In this folder, create new TypeScript file, named product.service.ts contain method call web api
import { Injectable } from '@angular/core';
import { Http, Response, Headers, Request, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import { Product } from '../entities/product.entity';
@Injectable()
export class ProductService {
private BASE_URL: string = 'http://localhost:9090/api/product/';
constructor(
private http: Http
) { }
create(product: Product) {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
let body = JSON.stringify(product);
return this.http.post(this.BASE_URL + 'create', body, options)
.map((res: Response) => res.json());
}
}
Create Component
Create new TypeScript file, named app.component.ts in src\app folder.
import { Component, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { Observable } from 'rxjs/Observable';
import { ProductService } from './services/product.service';
import { Product } from './entities/product.entity';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
productForm: any;
constructor(
private formBuilder: FormBuilder,
private productService: ProductService
) { }
ngOnInit() {
this.productForm = this.formBuilder.group({
name: '',
price: 0,
quantity: 0,
status: true
});
}
save(event: any) {
this.productService.create(this.productForm.value).subscribe(data => {
alert('Success');
});
}
}
Create View
Create new file, named app.component.html in src\app folder.
<h3>Add Product</h3>
<form [formGroup]="productForm" (ngSubmit)="save($event)">
<table>
<tr>
<td>Name</td>
<td>
<input formControlName="name" type="text" required="required">
</td>
</tr>
<tr>
<td>Price</td>
<td>
<input formControlName="price" type="number" required="required">
</td>
</tr>
<tr>
<td>Quantity</td>
<td>
<input formControlName="quantity" type="number" required="required">
</td>
</tr>
<tr>
<td>Status</td>
<td>
<input formControlName="status" type="checkbox">
</td>
</tr>
<tr>
<td> </td>
<td>
<button type="submit">Save</button>
</td>
</tr>
</table>
</form>
Add Components and Services to Module
In app.module.ts file in src\app folder. Add new components and new services to module
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { ProductService } from './services/product.service';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpModule,
FormsModule,
ReactiveFormsModule
],
providers: [
ProductService
],
bootstrap: [AppComponent]
})
export class AppModule { }
Run Application
In Terminal windows in Visual Studio Code and type: ng serve –open, program will open url http://localhost:4200/ on browser
Output
References
I recommend you refer to the books below to learn more about the knowledge in this article:
- Pro Angular 6
- Angular 6 for Enterprise-Ready Web Applications: Deliver production-ready and cloud-scale Angular web apps
- ng-book: The Complete Guide to Angular
- Angular in Action
- Mastering TypeScript – Second Edition
- Pro TypeScript: Application-Scale JavaScript Development
- MongoDB: The Definitive Guide: Powerful and Scalable Data Storage
- MongoDB Basics
- Mongoose for Application Development
- Pro Express.js: Master Express.js: The Node.js Framework For Your Web Development
- Express in Action: Writing, building, and testing Node.js applications