Call GET HTTP Method with Express.JS Web API and MongoDB in Angular 6


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 LearnAngular5withRealApps_Server folder and select to this folder in Visual Studio Code

Use the following command to install Mongoose:

npm install mongoose --save

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




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 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;

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.get('/product/findAll', ProductAPI.findAll);

module.exports = router;




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)
});

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 new folder named learnangular5withrealapps and select to this folder in Visual Studio Code

Open Terminal windows in Visual Studio Code and type: npm install -g @angular/cli to install Angular 6




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 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 } 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
    ) { }

    findAll(): Observable<Product[]> {
        return this.http.get(this.BASE_URL + 'findAll')
            .map((res: Response) => {
                return res.json();
            })
            .catch((error: any) => {
                return Observable.throw(new Error(error.status));
            });
    }

}

Create new TypeScript file, named app.component.ts in src\app folder.

import { Component, OnInit } from '@angular/core';
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 {

    products: Product[];

    constructor(
        private productService: ProductService
    ) { }

    ngOnInit() {
        this.loadData();
    }

    loadData(): void {
        this.productService.findAll().subscribe(
            res => {
                this.products = res;
            },
            error => {
                console.log(error);
            }
        );
    }

}

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>

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 { AppComponent } from './app.component';

import { ProductService } from './services/product.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpModule
  ],
  providers: [
    ProductService
  ],
  bootstrap: [AppComponent]
})

export class AppModule { }




In Terminal windows in Visual Studio Code and type: ng serve –open, program will open url http://localhost:4200/ on browser

I recommend you refer to the books below to learn more about the knowledge in this article: