Wednesday 25 October 2023

Consume NodeJS API using Angular step by step Example

 Continuing from previous post of NodeJS and MongoDB step by step Example, now going to consume NodeJS API using Angular.


Below is the folder structure of Angular:


>ng new angularconsumeapi

>cd angularconsumeapi

>code .

>ng serve --port 3000 --open

>ng generate component project

>ng generate service shared/api


I. Add code in EnquiryModel.ts

Code Snippet:-

export class EnquiryModel{
    //This should be same as Table column name
    EnquiryId:number=0;
    Name:string='';
    MobileNo:number=0;
    EmailID:string='';
    ProjID:number=0
}

II. Add code in ProjectModel.ts

Code Snippet:-

export class ProjectModel{
    //This should be same as Table column name
    ProjID:number=0;
    ProjName:string='';
    ProjType:string=''
}

III. Add code in api.service.ts

Code Snippet:-

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import { Observable } from 'rxjs';
import{map} from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  private postString:string="http://localhost:5000/";
  constructor(private _http:HttpClient) { }

  AddNewProject(data:any):Observable<any>{
    return this._http.post<any>(this.postString+"NewProject",data).pipe(
      map((res:any)=>{
        return res;
      })
    )
  }

  GetProjectDetails():Observable<any>{
    return this._http.get<any>(this.postString+"AllProject").pipe(
      map((res:any)=>{
        return res;
      })
    )
  }

  AddNewEnquiry(data:any):Observable<any>{
    return this._http.post<any>(this.postString+"NewEnquiry",data).pipe(
      map((res:any)=>{
        return res;
      })
    )
  }

  GetEnquiryDetailsByPID(id:number):Observable<any>{
    return this._http.get<any>(this.postString+"EnquiryByPID/"+id).pipe(
      map((res:any)=>{
        return res;
      })
    )
  }

}

IV. Add code in app-routing.module.ts

Code Snippet:-

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ProjectComponent } from './project/project.component';

const routes: Routes = [
  {
    path:'',component:ProjectComponent
  },
  {
    path:'project',component:ProjectComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }


V. Add code in app.component.html

Code Snippet:-

<router-outlet></router-outlet>

VI. Add code in app.module.ts

Code Snippet:-

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {ReactiveFormsModule} from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { ProjectComponent } from './project/project.component';

@NgModule({
  declarations: [
    AppComponent,
    ProjectComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

VII. Add below bootstrap cdn link in index.html

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>

VIII. Add code in project.component.html

Code Snippet:-

<nav class="navbar">
    <div class="container-fluid">
        <h2>Project Enquiry Demo</h2>

        <table class="table">
            <thead>
                <tr class="trBackground">
                    <th><button class="btn btn-info" type="button"
                        data-bs-toggle="modal" data-bs-target="#addProjectModal">Add Project</button>
                    &nbsp;
                        <button class="btn btn-info" type="button"
                        data-bs-toggle="modal" data-bs-target="#addEnquiryModal">Add Enquiry</button>
                    </th>
                </tr>
            </thead>
        </table>

        <div>
        <form [formGroup]="formValue">
        <h2>Show Enquiry based on Project</h2>
              <label for="Email" class="form-label">Select Project Id:</label>
              <select class="form-control" #t (change)="storeChangePid(t.value)" formControlName="pid">
                <!-- <option value="0">--Select--</option>   -->
                <option *ngFor="let proj of allProjectDetails"  
                        value={{proj.ProjID}}>{{proj.ProjName}}  
                </option>  
              </select>
            <br/>
            <button type="button" class="btn btn-success" (click)="showEnquiries()">Show Enquiries</button>
            <br/>
            <table class="table">
              <thead>
                <tr class="trBackground">
                <th scope="col">Name</th>
                <th scope="col">Mobile No</th>
                <th scope="col">Email Id</th>
                <th scope="col">Project Id</th>
                </tr>
              </thead>
              <tbody>
                <tr *ngFor="let data of EnquiryDetails">
                  <td>{{data.Name}}</td>
                  <td>{{data.MobileNo}}</td>
                  <td>{{data.EmailID}}</td>
                  <td>{{data.ProjID}}</td>
                </tr>
              </tbody>
            </table>
          </form>
          </div>

  <!-- Add Project Modal -->
  <div class="modal fade" id="addProjectModal" tabindex="-1" aria-labelledby="projectModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h1 class="modal-title fs-5" id="projectModalLabel">Add new Project</h1>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <form [formGroup]="formValue">
            <div class="mb-3">
              <label for="FName" class="form-label">Enter Project Id</label>
              <input type="email" class="form-control" required formControlName="pid" id="pid" placeholder="Enter Project Id"/>
            </div>
            <div class="mb-3">
              <label for="FName" class="form-label">Enter Project Name</label>
              <input type="email" class="form-control" required formControlName="pname" id="pname" placeholder="Enter Project Name"/>
            </div>
            <div class="mb-3">
              <label for="FName" class="form-label">Enter Project Type </label>
              <input type="radio" id="ptypeo" name="ptype" value="On Going" formControlName="ptype"/>On Going
              <input type="radio" id="ptypec" name="ptype" value="Comming Soon" formControlName="ptype"/>Comming Soon
            </div>
          </form>
           {{formValue.value|json}}
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          <button type="button" class="btn btn-success" data-bs-dismiss="modal" (click)="addProject()">Add Project</button>
        </div>
      </div>
    </div>
  </div>

  <!-- Add Enquiry Modal -->
  <div class="modal fade" id="addEnquiryModal" tabindex="-1" aria-labelledby="enquiryModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h1 class="modal-title fs-5" id="enquiryModalLabel">Add new Enquiry</h1>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <form [formGroup]="formValue">
            <div class="mb-3">
              <label for="EID" class="form-label">Enquiry Id</label>
              <input type="number" class="form-control" required formControlName="eid" id="eid" placeholder="Enter Enquiry Id"/>
            </div>
            <div class="mb-3">
              <label for="EName" class="form-label">Enter Name</label>
              <input type="text" class="form-control" required formControlName="ename" id="ename" placeholder="Enter Name"/>
            </div>
            <div class="mb-3">
              <label for="Mob" class="form-label">Enter Mobile No</label>
              <input type="number" class="form-control" required formControlName="mob" id="mob" placeholder="Enter Mobile No"/>
            </div>
            <div class="mb-3">
              <label for="Email" class="form-label">Enter Email No</label>
              <input type="email" class="form-control" required formControlName="email" id="email" placeholder="Enter Email Id"/>
            </div>
            <div class="mb-3">
              <label for="Email" class="form-label">Select Project Id</label>
              <select id="pid" formControlName="pid">
                <option value="0">--Select--</option>  
                <option *ngFor="let proj of allProjectDetails"  
                        value={{proj.ProjID}}>{{proj.ProjName}}  
                </option>  
              </select>
            </div>
          </form>
           {{formValue.value|json}}
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          <button type="button" class="btn btn-success" data-bs-dismiss="modal" (click)="addEnquiry()">Add Project</button>
        </div>
      </div>
    </div>
  </div>

    </div>
</nav>

IX. Add code in project.component.ts

Code Snippet:-

import { Component,OnInit } from '@angular/core';
import {FormBuilder, FormGroup } from '@angular/forms';
import { ProjectModel } from 'src/ProjectModel';
import { EnquiryModel } from 'src/EnquiryModel';
import { ApiService } from '../shared/api.service';

@Component({
  selector: 'app-project',
  templateUrl: './project.component.html',
  styleUrls: ['./project.component.scss']
})
export class ProjectComponent implements OnInit {
  formValue!:FormGroup;
  projectModelObject:ProjectModel=new ProjectModel();
  enquiryModelObject:EnquiryModel=new EnquiryModel();
  allProjectDetails:any;
  EnquiryDetails:any;

  constructor(private _formBuilder:FormBuilder,private _apiService:ApiService){}

  ngOnInit():void{
    this.formValue=this._formBuilder.group({
      pid:[''],
      pname:[''],
      ptype:[''],

      eid:[''],
      ename:[''],
      mob:[''],
      email:[''],
      });
      this.getAllProject();
  }

  addProject(){
    this.projectModelObject.ProjID=this.formValue.value.pid;
    this.projectModelObject.ProjName=this.formValue.value.pname;
    this.projectModelObject.ProjType=this.formValue.value.ptype;

    console.log(this.projectModelObject);

     this._apiService.AddNewProject(this.projectModelObject).subscribe({
     next:(res)=>{console.log(res),alert('Project added successfully!'),
     this.formValue.reset()},
     error:(e)=>{console.log(e),alert("Error occured!")}
 
    })
  }

  getAllProject(){
    this._apiService.GetProjectDetails().subscribe({
    next:(res)=>{this.allProjectDetails=res},
    error:(e)=>{console.log(e),alert("Error occured!")}
    })
  }

  addEnquiry(){
    this.enquiryModelObject.EnquiryId=this.formValue.value.eid;
    this.enquiryModelObject.Name=this.formValue.value.ename;
    this.enquiryModelObject.MobileNo=this.formValue.value.mob;
    this.enquiryModelObject.EmailID=this.formValue.value.email;
    this.enquiryModelObject.ProjID=this.formValue.value.pid;

    console.log(this.enquiryModelObject);

     this._apiService.AddNewEnquiry(this.enquiryModelObject).subscribe({
     next:(res)=>{console.log(res),alert('Enquiry added successfully!'),
     this.formValue.reset()},
     error:(e)=>{console.log(e),alert("Error occured!")}
    })
  }

  storeChangePid(data:string){
    console.log(parseInt(data));
    this.enquiryModelObject.ProjID=parseInt(data);
  }

  showEnquiries(){
    console.log(this.enquiryModelObject.ProjID);

    this._apiService.GetEnquiryDetailsByPID(this.enquiryModelObject.ProjID).subscribe({
    next:(res)=>{this.EnquiryDetails=res},
    error:(e)=>{console.log(e),alert("Error occured!")}
    })

    console.log(this.EnquiryDetails);
  }

}

Now we can add below data and check in MongoDB if data are saving

                                        


--To check in MongoDB

To open MongoDB
>cd C:\Users\subas.patel\Documents\Subas\Softwares\mongosh-1.6.2-win32-x64\mongosh-1.6.2-win32-x64\bin>mongosh

> use ABCBuilders
> db.ProjectInfo.find()
> db.EnquiryInfo.find()


                                       

Next post will see, write API in ASP.NET Core and save data in MongoDB using same React and Angular UI.

Consume NodeJS API using React step by step Example

Continuing from previous post of NodeJS and MongoDB step by step Example, now going to consume NodeJS API using React.

Below is the folder structure of React:

>npx create-react-app reactconsumeapi

>cd reactconsumeapi

>npm start

>npm i axios --save

I. Add folder Components under src>>AddEnquiry.jsx files and add code

Code Snippet:-

import React from "react";
import axios from "axios";
export default class AddEnquiry extends React.Component
{
    constructor(){
        super();
        this.state={
            eid:0,
            name:'',
            mobno:0,
            email:'',
            pid:0,
            proj:[]
        }
    }
    setData=(e)=>{
        e.preventDefault();
        this.setState({[e.target.name]:e.target.value});
    }
    componentDidMount() /*After the React component is rendered and
     when the page is loading
    this method will be  */
    {
        axios.get("http://localhost:5000/AllProject").then(r=>{
            console.log('Enquiry');
            console.log(r.data);
            this.setState({proj:r.data});
        })
    }
    AddEnquiry=(e)=>{
       e.preventDefault();
       let enquiry={
        EnquiryId:parseInt(this.state.eid),
        Name:this.state.name,
        MobileNo:parseInt(this.state.mobno),
        EmailID:this.state.email,
        ProjID:parseInt(this.state.pid)
       }
       console.log(enquiry);
       axios.post("http://localhost:5000/NewEnquiry",enquiry).then(r=>{
        console.log(r.data);
       })
    }
    render()
    {
        return(
            <>
            <h1>Add Enquiry for Project</h1>
            <table border="1" style={{backgroundColor:"lightcoral",border:'5px solid red'}}>
                <tbody>
                <tr>
                    <td>Enquiry ID:</td>
                    <td><input type="text" name="eid" onInput={this.setData}/></td>
                </tr>
                <tr>
                    <td>Enter Name:</td>
                    <td><input type="text" name="name" onInput={this.setData}/></td>
                </tr>
                <tr>
                    <td>Enter Mobile No:</td>
                    <td><input type="text" name="mobno" onInput={this.setData}/></td>
                </tr>
                <tr>
                    <td>Enter EmailID:</td>
                    <td><input type="text" name="email" onInput={this.setData}/></td>
                </tr>
                <tr>
                    <td>Select Project ID:</td>
                    <td><select name="pid" onChange={this.setData}>
                        {
                            this.state.proj.map(r=>
                                <option value={r.ProjID} key={r.ProjID}>
                                    {r.ProjName}
                                </option>
                            )
                        }
                        </select></td>
                </tr>
                <tr>
                    <tr>
                        <button onClick={this.AddEnquiry}>Add Enquiry </button>
                    </tr>
                </tr>
                </tbody>
            </table>
            </>
        )
    }
}

II. Add folder Components under src>>AddProject.jsx files and add code

Code Snippet:-

import React from "react";
import axios from "axios";
export default class AddProject extends React.Component
{
    constructor()
    {
        super()
        {
            this.state={
                pid:0,
                pname:'',
                ptype:''
            }
        }
    }

    setData=(e)=>{
        e.preventDefault();
        this.setState({[e.target.name]:e.target.value})
    }

    AddData=(e)=>{
        e.preventDefault();
        let project={
            ProjID:this.state.pid,
            ProjName:this.state.pname,
            ProjType:this.state.ptype
        };
        //It is calling from NodeJS api NewProject Method
        axios.post("http://localhost:5000/NewProject",project).then(r=>{
            console.log(r.data);
        })
    }

    render()
    {
        return(
            <>
            <h1>Adding new Project</h1>
            <form>
                <table style={{backgroundColor:'yellow',color:'red',border:"5px solid green"}}>
                    <tbody>
                        <tr>
                            <td>Enter Project Id</td>
                            <td>
                                <input type="text" name="pid" onInput={this.setData}/>
                            </td>
                        </tr>
                        <tr>
                            <td>Enter Project Name</td>
                            <td>
                            <input type="text" name="pname" onInput={this.setData}/>
                            </td>
                        </tr>
                        <tr>
                            <td>Enter Project Type</td>
                            <td>
                            <input type="radio" name="ptype" value="On Going" onChange={this.setData}/> OnGoing
                            <input type="radio" name="ptype" value="Coming Soon" onChange={this.setData}/> Coming Soon
                            </td>
                        </tr>
                        <tr>
                            <td>
                            <button type="submit" onClick={this.AddData} >New Project</button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </form>
            </>
        )
    }
   
}

III. Add folder Components under src>>ShoProjectByEnquiry.jsx files and add code

Code Snippet:-

import React from "react";
import axios from "axios";
export default class ShowProjectByEnquiry extends React.Component
{
   constructor()
   {
    super();
    this.state={
    pid:0,
    proj:[],
    enquiry:[],
    project:[]
      }
   }
   componentDidMount() /*After the React component is rendered and
     when the page is loading
    this method will be  */
    {
        axios.get("http://localhost:5000/AllProject").then(r=>{
            console.log('ShowProjectByEnquiry');
            console.log(r.data);
            this.setState({proj:r.data});
        })
    }
    setData=(e)=>{
        e.preventDefault();
        this.setState({[e.target.name]:e.target.value});
    }
    ShowEnquiry=(e)=>{
        e.preventDefault();
        console.log(this.state.pid);
        axios.get("http://localhost:5000/ProjectByID/"+parseInt(this.state.pid)).then(r=>
        {
            console.log(r.data);
            this.setState({project:r.data});
        })
        axios.get("http://localhost:5000/EnquiryByPID/"+parseInt(this.state.pid)).then(r=>
        {
            console.log(r.data);
            this.setState({enquiry:r.data});
        })
       
    }

    render()
    {
        return(
            <>
            <h1>Show Enquiry based on Project</h1>
            <form>
                <table border="1">
                <tbody>
                <tr>
                    <td>Select Project ID:</td>
                    <td><select name="pid" onChange={this.setData}>
                        {
                            this.state.proj.map(r=>
                                <option value={r.ProjID} key={r.ProjID}>
                                    {r.ProjName}
                                </option>
                            )
                        }
                        </select>
                    </td>
                </tr>
                <tr>
                    <button onClick={this.ShowEnquiry}>Show Enquiries</button>
                </tr>
               
                    </tbody>
                </table>
                <hr/>
                 {this.state.project.map(r=>
                <h2>Project Type:{r.ProjectType} </h2>
                 )
            }
                <h2>Count:{this.state.enquiry.length}</h2>
                <table style={{border:'5px dotted green'}}>
                    <tbody>
                        <tr>
                            <th>Name</th>
                            <th>Mobile No</th>
                            <th>Email ID</th>
                            <th>Project ID</th>
                        </tr>
                        {
                            this.state.enquiry.map(r=>
                                <tr>
                                    <td>{r.Name}</td>
                                    <td>{r.MobileNo}</td>
                                    <td>{r.EmailID}</td>
                                    <td>{r.ProjID}</td>
                                </tr>
                                )
                        }
                    </tbody>
                </table>

            </form>
            </>
        )
    }

}

IV. Add code in index.js

Code Snippet:-

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import AddProject from './components/AddProject';
import AddEnquiry from './components/AddEnquiry';
import ShowProjectByEnquiry from './components/ShowProjectByEnquiry';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <>
  <AddProject/>
  <AddEnquiry/>
  <ShowProjectByEnquiry/>
  </>
);

V. Glimpse of package.json

Now we can add below data and check in MongoDB if data are saving


 To open MongoDB
>cd C:\Users\subas.patel\Documents\Subas\Softwares\mongosh-1.6.2-win32-x64\mongosh-1.6.2-win32-x64\bin>mongosh

> use ABCBuilders
> db.ProjectInfo.find()
> db.EnquiryInfo.find()


Next post will see, consuming same NodeJS API using Angular.