Call PUT 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 update data from client

var mongoose = require('mongoose');
var Product = require('../schemas/product.schema');

var ProductAPI = {

    update: function (request, response) {

        Product.findByIdAndUpdate(
            request.body._id,
            {
                name: request.body.name,
                price: request.body.price,
                quantity: request.body.quantity,
                status: request.body.status
            },
            function (error, result) {
                if (error) {
                    throw error;
                } else {
                    response.status(200).json(result);
                }
            }
        );
    }

};

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

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

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

    update(product: Product) {
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        let body = JSON.stringify(product);
        return this.http.put(this.BASE_URL + 'update', body, options)
                    .map((res: Response) => res.json());
    }

}




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({
            _id: '',
            name: '',
            price: 0,
            quantity: 0,
            status: true
        });
    }

    save(event: any) {
		this.productService.update(this.productForm.value).subscribe(data => {
			alert('Success');
		});
	}

}

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

<h3>Update Product</h3>
<form [formGroup]="productForm" (ngSubmit)="save($event)">
    <table>
        <tr>
            <td>Id</td>
            <td>
                <input formControlName="_id" type="text" required="required">
            </td>
        </tr>
        <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>&nbsp;</td>
            <td>
                <button type="submit">Save</button>
            </td>
        </tr>
    </table>
</form>

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




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: