DevRocket
Tutorials

Backend Integration

This guide explains how to set up and use APIs for communication between an Angular frontend and a NestJS backend. You’ll also learn how to handle authentication, error messages, and API calls using reusable services.

Step 1: Create an API Endpoint in NestJS

  1. Generate a Custom Module: Run the following commands to generate a new module for your API:

    cd backend
    nest generate module custom
  2. Generate a Custom Module: Run the following command to generate a new module for your API:

    nest generate module custom
  3. Add a Controller: Create a controller to handle API requests:

    nest generate controller custom

    This will create a custom.controller.ts file in the custom folder.

  4. Add API Logic in the Controller: Example custom.controller.ts:

    import { Controller, Post, Body, HttpException, HttpStatus } from '@nestjs/common';
     
    @Controller('custom')
    export class CustomController {
      @Post()
      async updateUser(@Body() body: { email: string }) {
        if (!body.email) {
          throw new HttpException('Email is required', HttpStatus.BAD_REQUEST);
        }
     
        // Simulated logic for updating a user
        return { message: 'User updated successfully', email: body.email };
      }
    }
  5. Register the Module in app.module.ts: Add the CustomModule to the imports array in app.module.ts:

    import { Module } from '@nestjs/common';
    import { CustomModule } from './custom/custom.module';
     
    @Module({
      imports: [
         // other imports
         CustomModule,
      ],
      // ...
    })
    export class AppModule {}

Step 2: Set Up an API Service in Angular

  1. Create an API Service: Generate a service using Angular CLI:

    cd ../frontend
    ng generate service api

    Update the api.service.ts file:

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { catchError } from 'rxjs/operators';
    import { throwError } from 'rxjs';
     
    @Injectable({
      providedIn: 'root',
    })
    export class ApiService {
     
      constructor(private http: HttpClient) {}
     
      post<T>(endpoint: string, body: any) {
        return this.http.post<T>('custom', body).pipe(
          catchError((error) => {
            console.error('API Error:', error);
            return throwError(() => new Error(error.message || 'Server error'));
          })
        );
      }
    }

Step 2: Call the API from Angular

  1. Use the API Service: Example in a component:

    import { Component } from '@angular/core';
    import { ApiService } from './services/api.service';
     
    @Component({
      selector: 'app-user-profile',
      template: `
        <button (click)="saveUser()" class="btn btn-primary">
          {{ isLoading ? 'Loading...' : 'Save' }}
        </button>
      `,
    })
    export class UserProfileComponent {
      isLoading = false;
     
      constructor(private apiService: ApiService) {}
     
      saveUser() {
        this.isLoading = true;
     
        this.apiService.post<{ message: string }>('user', { email: 'new@gmail.com' }).subscribe({
          next: (response) => {
            console.log(response.message);
            this.isLoading = false;
          },
          error: (error) => {
            console.error(error.message);
            this.isLoading = false;
          },
        });
      }
    }
  2. Test the API:

    • Start the backend server using:
      npm run start:dev
    • Start the frontend server using:
      ng serve
    • Navigate to http://localhost:4200 and test the "Save" button.

Step 3: Handle Protected API Calls [TODO]

Congratulations!

You’ve successfully set up API communication between Angular and NestJS. Use the modular structure for scalable development, and secure API calls with proper authentication mechanisms.

On this page