The main objectives of this article are:
(Step 1)
- Create HTTP GET endpoint in nestjs application
- Consume GET API and render the response in angular component
Create HTTP Get Endpoint In NestJS Application:
In 'SuperHeroesService' implement logic to fetch the data from the MongoDB
NestJS_App/src/super-heroes/super-heroes.service.ts:
import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { SuperHeroes, SuperHeroesDocument } from './schema/super-heroes.schema'; @Injectable() export class SuperHeroesService { constructor( @InjectModel(SuperHeroes.name) private superHeroModel: Model<SuperHeroesDocument>, ) {} async getAll():Promise<SuperHeroes[]>{ return await this.superHeroModel.find().exec(); } }
- (12-14) The 'find()' method fetches all documents from the MongoDB collection.
nest g co super-heroes --no-spec
Now let's add the HTTP Get endpoint in our 'SuperHeroesController'.
NestJS_App/src/super-heroes/super-heroes.controller.ts:
import { Controller, Get } from '@nestjs/common'; import { SuperHeroesService } from './super-heroes.service'; @Controller('super-heroes') export class SuperHeroesController { constructor(private superHeroService:SuperHeroesService){} @Get() async getAll(){ return await this.superHeroService.getAll(); } }
- (Line: 4) To make our 'SuperHeroesController' class a controller it has to be decorated with '@controller' that loads from the '@nestjs/common'. The '@controller' takes a string as input, that string will be the part of the endpoint.
- (Line: 7) Inject our 'SuperHeroesService'.
- (Line: 9) The '@Get()' decorator makes our method to consumed only for the HTTP Get request.
Create An Angular Component Like 'AllSuperHeroes':
Let's create an angular component like 'AllSuperHeroes' inside of the 'super-heroes' folder(new folder).ng generate component super-heroes/all-super-heroes --skip-tests
Now configure routing for 'all-super-heroes.component.ts' in 'app-routing.module.ts'
Angular_App/src/app/super-heroes/all-super-heroes/all-super-heroes.component.ts:
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AllSuperHeroesComponent } from './super-heroes/all-super-heroes/all-super-heroes.component'; const routes: Routes = [ { path: '', component: AllSuperHeroesComponent, }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], }) export class AppRoutingModule {}
- (Line: 6-9) The 'AllSuperHeroesComponent' is configured to the home page URL.
Create 'SuperHeroes' Model In Angular Application:
Let's create an API response model like 'SuperHeroes' in our angular application.
ng generate interface super-heroes/super-heroes
Angular_App/src/app/super-heroes/super-heroes.ts:
export interface SuperHeroes { _id: string; name: string; franchise: string; powers: string; imageUrl: string; }
Create Service To Invoke API Calls In Angular Application:
Let's create a service file in our angular application in which we will implement all logic for invoking the API call.
ng generate service super-heroes/super-heroes --skip-tests
Angular_App/src/app/super-heroes/super-heroes.service.ts:
import { Injectable } from '@angular/core'; import {HttpClient} from '@angular/common/http' import { SuperHeroes } from './super-heroes'; @Injectable({ providedIn: 'root' }) export class SuperHeroesService { constructor(private http:HttpClient) { } get(){ return this.http.get<SuperHeroes[]>("http://localhost:3000/super-heroes") } }
- (Line: 5-8) To make our 'SuperHeroesService' a service entity it has to be decorated with the '@Injectable' that loads from the '@angular/core'.
- (Line: 10) Injected the 'HttpClient' instance that loads from the '@angular/common/http'.
- (Line: 12-14) Here invoking the get API call using the 'HttpClient.get<T>()' method.
Angular_App/src/app/app.module.ts:
import { HttpClientModule } from '@angular/common/http'; // existing code hidden for display purpose @NgModule({ imports: [ HttpClientModule ] }) export class AppModule { }
Invoke API And Render The API Response In 'AllSuperHeroes' Angular Component:
Let's implement the logic to call HTTP Get API and then render the API response in the 'AllSuperHeroes' angular component.
Angular_App/src/app/super-heroes/all-super-heroes/all-super-heroes.component.ts:
import { Component, OnInit } from '@angular/core'; import { SuperHeroes } from '../super-heroes'; import { SuperHeroesService } from '../super-heroes.service'; @Component({ selector: 'app-all-super-heroes', templateUrl: './all-super-heroes.component.html', styleUrls: ['./all-super-heroes.component.css'], }) export class AllSuperHeroesComponent implements OnInit { constructor(private superHeroService: SuperHeroesService) {} superHeroes: SuperHeroes[] = []; ngOnInit(): void { this.getAll(); } getAll() { this.superHeroService.get().subscribe((data) => { this.superHeroes = data; }); } }
- (Line: 7) The 'templateUrl' property is configured with the path of the HTML file of the component.
- (Line: 8) The 'styleUrls' property takes an array of CSS files that needed by our component.
- (Line: 10) To make our 'AllSuperHeroesComponent' an angular component it has to be decorated with the '@Component' decorator. Here our component class implements the 'OnInit' so we have to implement the 'ngOnInit' life cycle method in our component.
- (Line: 11) Inject our 'SuperHeroesService'.
- (Line: 13) Initialized the variable 'superHeroes' in which we are going to store our API response.
- (Line: 19-22) Invoking the API and response is assigned to the 'superHeroes' variable
- (Line: 15-17) The 'ngOnInit' is a life cycle method executed on the component invoked. In this method, we are calling our API invoking method.
<div class="container mt-2"> <div class="row row-cols-1 row-cols-md-3 g-2"> <div class="col" *ngFor="let item of superHeroes"> <div class="card"> <img src="{{ item.imageUrl }}" class="card-img-top" alt="..." /> <div class="card-body"> <h5 class="card-title">{{ item.name }}</h5> <p class="card-text"><b>Franchise:</b> {{ item.franchise }}</p> <p class="card-text"><b>Powers:</b> {{item.powers}}</p> </div> </div> </div> </div> </div>
- In angular to render dynamic data into the component HTML file, we use "{{dynamic_component_property}}".
- In angular to loop any HTML content, we use '*ngFor'
- (Line: 3) Here looping our bootstrap card to render the collection of data in the 'superHeroes' component variable
NestJS_App/src/main.ts:
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.enableCors(); await app.listen(3000); } bootstrap();
- (Line: 6) The 'app.enableCors()' make our API can be consumed by any client.
(Step 1)
(Step: 2)
In the next article, we implement the create operation.
Support Me!
Buy Me A Coffee
PayPal Me
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-5 | NestJS(v9) | Angular(v14) | MongoDB | CRUD Example
Part-6| NestJS(v9) | Angular(v14) | MongoDB | CRUD
Part-7 | NestJS(v9) | Angular(v14) | MongoDB | CRUD Example
Part-5 | NestJS(v9) | Angular(v14) | MongoDB | CRUD Example
Part-6| NestJS(v9) | Angular(v14) | MongoDB | CRUD
Part-7 | NestJS(v9) | Angular(v14) | MongoDB | CRUD Example
Comments
Post a Comment