The main objectives of this article are:
Now let's configure route for our 'AddSuperHeroesComponent'.
- Create HTTP Post Endpoint In NestJS Application.
- Angular Application Add A Form To Create New Item.
Create HTTP Post Endpoint In NestJS Application:
In our service file implement the logic to save a new document to the MongoDB.
NestJS_App/src/super-heroes/super-heroes.service.ts:
async create(superHeroes: SuperHeroes) { const newSuperHeroes = new this.superHeroModel(superHeroes); return await newSuperHeroes.save(); }
- Here our payload 'superHeroes' is converted to the MongoDB collection model document type and then invoking the 'save()' method that saves our new document into the MongoDB.
NestJS_App/src/super-heroes/super-heroes.controller.cs:
import { Body, Controller, Get, Post } from '@nestjs/common'; import { SuperHeroes } from './schema/super-heroes.schema'; import { SuperHeroesService } from './super-heroes.service'; @Controller('super-heroes') export class SuperHeroesController { constructor(private superHeroService:SuperHeroesService){} @Post() async createSuperHeroes(@Body() superHeroes: SuperHeroes) { const newBook = await this.superHeroService.create(superHeroes); return newBook; } }
- (Line: 9) The '@Post()' decorator makes our action method only invoke for the HTTP Post request.
- (Line: 10) The '@Body()' decorator helps to read the form data. Here reading the user posted form data as 'SuperHeroes' type.
- (Line: 11) Invoking the 'create()' method of service to save our new item
- (Line: 12) Finally return the newly created document as a response.
Create A New Angular Component Like 'AddSuperHerosComponent':
Let's create a new component in our angular application like 'AddSuperHereosComponent'.
ng generate component super-heroes/add-super-heroes
Now let's configure route for our 'AddSuperHeroesComponent'.
Angular_App/src/app/app-routing.module.ts:
import { AddSuperHeroesComponent } from './super-heroes/add-super-heroes/add-super-heroes.component'; // existing code hidden for display purpose const routes: Routes = [ { path: 'add-super-hero', component: AddSuperHeroesComponent, }, ];
Implement HTTP Post API Call Logic In Angular Service:
Let's create a new modal for our payload like 'CreateOrUpdateSuperHero'
ng generate interface super-heroes/create-or-update-super-hero
export interface CreateOrUpdateSuperHero { name: string; franchise: string; powers: string; imageUrl: string; }
Let's implement the HTTP Post call logic in our 'SuperHeroesService'.
Angular_App/src/app/super-heroes/super-heroes.service.ts:
create(superHero: CreateOrUpdateSuperHero) { return this.http.post<SuperHeroes>( 'http://localhost:3000/super-heroes', superHero ); }
- Here using 'http.post()' method we can trigger the HTTP Post request. So payload needs to be passed along with the request.
Implement A Form To Create New Item:
Let's implement the form for creating a new item by invoking the HTTP post request in the 'AddSuperHeroesComponent'.
src/app/super-heroes/add-super-heroes/add-super-heroes.component.ts:
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { CreateOrUpdateSuperHero } from '../create-or-update-super-hero'; import { SuperHeroes } from '../super-heroes'; import { SuperHeroesService } from '../super-heroes.service'; @Component({ selector: 'app-add-super-heroes', templateUrl: './add-super-heroes.component.html', styleUrls: ['./add-super-heroes.component.css'], }) export class AddSuperHeroesComponent implements OnInit { constructor( private superHeroesService: SuperHeroesService, private router: Router ) {} superHeroes: CreateOrUpdateSuperHero = { name: '', franchise: '', imageUrl: '', powers: '', }; ngOnInit(): void {} create() { this.superHeroesService.create(this.superHeroes).subscribe(() => { this.router.navigate(['/']); }); } }
- (Line: 14) Injected our 'SuperHeroService'.
- (Line: 15) Injected the 'Router' service that loads from the '@angular/router'.
- (Line: 18-23) The 'superHeroes' is our form model variable.
- (Line: 27-31) Invoking the HTTP Post call, on the success we redirect back to the home page.
<div class="container mt-2"> <legend>Create Item</legend> <form> <div class="mb-3"> <label for="txtName" class="form-label">Name</label> <input type="text" name="name" [(ngModel)]="superHeroes.name" class="form-control" id="txtName" /> </div> <div class="mb-3"> <label for="txtFranchise" class="form-label">Franchise</label> <input type="text" name="txtFranchise" [(ngModel)]="superHeroes.franchise" class="form-control" id="txtFranchise" /> </div> <div class="mb-3"> <label for="txtImageUrl" class="form-label">ImageUrl</label> <input type="text" name="txtImageUrl" [(ngModel)]="superHeroes.imageUrl" class="form-control" id="txtImageUrl" /> </div> <div class="mb-3"> <label for="txtPowers" class="form-label">Powers</label> <textarea class="form-control" name="powers" id="txtPowers" [(ngModel)]="superHeroes.powers" rows="3" ></textarea> </div> <button type="button" (click)="create()" class="btn btn-primary"> Create </button> </form> </div>
- Here enable 2-way model binding using '[(ngModel)]'. One more important thing here is that the input element must contain the 'name' attribute for 2-way model binding.
- Here all input fields enabled 2-way model binding with the 'superHeroes' form object.
- Click event can be registered like '(name_of_event)' and the event must register with the method in the 'ts' file so that on raise of event logic inside of the method gets executed.
Let's add the 'Create' button in 'AllSuperHeroesComponent' so on button click we will navigate to the 'AddSuperHeroesComponent'.
src/app/super-heroes/all-super-heroes/all-super-heroes.component.html:
<div class="container mt-2"> <div class="row mt-2"> <div class="col col-md-4 offset-md-4"> <a class="btn btn-primary" routerLink="/add-super-hero">Create</a> </div> </div> <div class="row row-cols-1 row-cols-md-3 g-2"> <!-- existing code hidden for display purpose --> </div> </div>
- Here 'Create' button which is an anchor tag element to which we can decorate angular attributes like 'routerLink'. The 'routerLink' navigate to the specified path with our reloading of the page.
(Step: 2)
(Step: 3)
In the next article, we will implement the update operation.
Video Session:
Wrapping Up:
Hopefully, I think this article delivered some useful information on NestJS (v9) and Angular(v4). using I love to have your feedback, suggestions, and better techniques in the comment section below.
Refer:
Part-3 | NestJS(v9) | Angular(v14) | MongoDB | CRUD Example
Part-4 | NestJS(v9) | Angular(v14) | MongoDB | CRUD Example
Part-6| NestJS(v9) | Angular(v14) | MongoDB | CRUD Example
Part-7 | NestJS(v9) | Angular(v14) | MongoDB | CRUD Example
Part-4 | NestJS(v9) | Angular(v14) | MongoDB | CRUD Example
Part-6| NestJS(v9) | Angular(v14) | MongoDB | CRUD Example
Part-7 | NestJS(v9) | Angular(v14) | MongoDB | CRUD Example
Support Me!
Buy Me A Coffee
PayPal Me
Comments
Post a Comment