Create Database
Create a database with the name is learn_angular_7. This database have 1 collection: Product collection
/* Create learn_angular_7 database */
use learn_angular_7
/* 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 LearnAngular7withRealApps_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 provides application/json data for the client
var mongoose = require('mongoose');
var Product = require('../schemas/product.schema');
var ProductAPI = {
findAll: function (request, response) {
Product.find({}, function (error, products) {
if (error) {
throw error;
} else {
response.status(200).json(products);
}
});
}
};
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_7');
var ProductAPI = require('./product.api');
router.get('/product/findAll', ProductAPI.findAll);
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
Test Rest API Server
At the root of server project run command: node server.js
Access Rest API use the following url: http://localhost:9090/api/product/findAll
Output
[
{"_id":"59eb397591876fae6628f17d","name":"Mobile 1","price":2,"quantity":4,"status":true},
{"_id":"59eb3a3991876fae6628f17e","name":"Mobile 2","price":5,"quantity":2,"status":false},
{"_id":"5a73bcda0f628d50d9dfe0a9","name":"Laptop 2","price":9,"quantity":3,"status":true},
{"_id":"5a73bd120f628d50d9dfe0c6","name":"Computer 1","price":15,"quantity":8,"status":false},
{"_id":"5a73e2f3ca031628a0701926","name":"Computer 2","price":20,"quantity":8,"status":true}
]
Create Client Project
Create new folder named learnangular7withrealapps and select to this folder in Visual Studio Code
Install Angular 7
Open Terminal windows in Visual Studio Code install Angular 7 as below:
- To install the CLI using npm, use command: npm install -g @angular/cli
- To create sample project with CLI, use command: ng new LearnAngular7WithRealApps
Structure of Project
Create Entity
Create new folder, named entities in src\app folder. In this folder, create new 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 file, named product.service.ts contain method call web api
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Product } from '../entities/product.entity';
@Injectable()
export class ProductService {
private BASE_URL: string = 'http://localhost:9090/api/product/';
constructor(
private httpClient: HttpClient
) { }
findAll() {
return this.httpClient.get(this.BASE_URL + 'find_all')
.toPromise()
.then(res => res as Product[]);
}
}
Create Component
Create new file, named app.component.ts in src\app folder.
import { Component, OnInit } from '@angular/core';
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 {
products: Product[];
constructor(
private productService: ProductService
) { }
ngOnInit() {
this.loadData();
}
loadData(): void {
this.productSercice.findAll().then(
res => {
this.products = res;
},
error => {
console.log(error);
}
);
}
}
Create View
Create new file, named app.component.html in src\app folder. In this view, show products list from component
<h3>Products List</h3>
<table border="1">
<tr>
<th>Id</th>
<th>Name</th>
<th>Status</th>
<th>Price</th>
<th>Quantity</th>
</tr>
<tr *ngFor="let product of products">
<td>{{product._id}}</td>
<td>{{product.name}}</td>
<td>{{product.status}}</td>
<td>{{product.price}}</td>
<td>{{product.quantity}}</td>
</tr>
</table>
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 { HttpClientModule } from '@angular/common/http';
import { ProductService } from './services/product.service';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
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