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 { }
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>
<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.
No comments:
Post a Comment