Integrating Angular with .NET Core Web API for Full-Stack Development

Integrating Angular with .NET Core Web API - Full-Stack Guide | Ayodhyya

Building a full-stack web application involves integrating a powerful frontend framework with a robust backend. Angular and .NET Core Web API form a great combination for building scalable, maintainable, and high-performing applications. This article explores how to integrate Angular with .NET Core Web API for full-stack development, covering key concepts, setup, and best practices.

Why Choose Angular and .NET Core Web API?

Advantages of Angular

  • Component-Based Architecture: Modular development with reusable UI components.
  • Two-Way Data Binding: Syncs data between the UI and model efficiently.
  • Dependency Injection: Built-in dependency management system.
  • Powerful CLI: Automates project setup, testing, and deployment.
  • Material Design Support: Provides pre-built UI components with Angular Material.

Advantages of .NET Core Web API

  • Cross-Platform Compatibility: Runs on Windows, Linux, and macOS.
  • High Performance: Optimized request handling and lightweight architecture.
  • Security Features: Built-in authentication and authorization mechanisms.
  • Entity Framework Core: Simplifies database interactions.
  • Scalability: Supports microservices and cloud deployments.

Setting Up the Development Environment

To integrate Angular with .NET Core Web API, follow these steps:

1. Install Prerequisites

Ensure you have the following installed:

  • Node.js & npm (for Angular development): Download
  • Angular CLI: Install using npm install -g @angular/cli
  • .NET SDK: Download
  • Visual Studio Code or Visual Studio: IDE for development
  • SQL Server or PostgreSQL (optional): Database management system

2. Create a .NET Core Web API Project

Run the following command to create a new API project:

mkdir FullStackApp && cd FullStackApp
 dotnet new webapi -n BackendAPI

This creates a basic Web API project.

3. Configure CORS in .NET Core

Modify Startup.cs to allow Angular to access the API:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowAngularApp",
            builder => builder.WithOrigins("http://localhost:4200")
                              .AllowAnyMethod()
                              .AllowAnyHeader());
    });
    services.AddControllers();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseCors("AllowAngularApp");
    app.UseRouting();
    app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}

4. Create an Angular Application

Navigate to the root directory and run:

ng new FrontendApp --style=scss
cd FrontendApp
ng serve

This generates an Angular project and starts a development server at http://localhost:4200/.

5. Connect Angular to .NET Core API

Create a proxy.conf.json file in the Angular root directory:

{
  "/api": {
    "target": "http://localhost:5000",
    "secure": false,
    "logLevel": "debug"
  }
}

Modify angular.json to use the proxy:

"serve": {
  "options": {
    "proxyConfig": "proxy.conf.json"
  }
}

6. Create a Model and API Controller in .NET Core

Define a simple model Product.cs:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

Create a controller ProductsController.cs:

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private static List<Product> products = new List<Product>
    {
        new Product { Id = 1, Name = "Laptop", Price = 999.99M },
        new Product { Id = 2, Name = "Phone", Price = 499.99M }
    };
    
    [HttpGet]
    public ActionResult<IEnumerable<Product>> GetProducts() => Ok(products);
}

7. Create an Angular Service to Fetch Data

Generate a service using the Angular CLI:

ng generate service product

Modify product.service.ts:

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

@Injectable({ providedIn: 'root' })
export class ProductService {
  private apiUrl = '/api/products';
  constructor(private http: HttpClient) {}
  getProducts(): Observable<any> {
    return this.http.get(this.apiUrl);
  }
}

8. Display Data in Angular Component

Modify app.component.ts:

import { Component, OnInit } from '@angular/core';
import { ProductService } from './product.service';

@Component({ selector: 'app-root', templateUrl: './app.component.html' })
export class AppComponent implements OnInit {
  products: any[] = [];
  constructor(private productService: ProductService) {}
  ngOnInit() {
    this.productService.getProducts().subscribe(data => this.products = data);
  }
}

Modify app.component.html:

<h2>Product List</h2>
<ul>
  <li *ngFor="let product of products">{{ product.name }} - ${{ product.price }}</li>
</ul>

9. Running the Full-Stack Application

  • Start the .NET Core Web API:
dotnet run --project BackendAPI
  • Start the Angular app:
ng serve

Now, navigate to http://localhost:4200/ to see the data from the API displayed in the Angular app.

Best Practices for Angular and .NET Core Integration

  1. Use DTOs (Data Transfer Objects): Avoid exposing database models directly.
  2. Enable Authentication: Use JWT-based authentication for securing APIs.
  3. Optimize API Calls: Implement caching and pagination to enhance performance.
  4. Use Environment Variables: Manage API URLs using environments.ts.
  5. Implement Lazy Loading: Load Angular modules on demand to improve efficiency.
  6. Use Angular Interceptors: Handle global error handling and attach tokens to requests.
  7. Logging and Monitoring: Implement logging in both frontend and backend using tools like Serilog and Angular Logger.

Conclusion

Integrating Angular with .NET Core Web API provides a powerful approach to building full-stack applications. By following best practices and leveraging the strengths of both frameworks, developers can create scalable, maintainable, and high-performance web applications. With proper structuring, authentication, and optimizations, this tech stack can support enterprise-grade applications with ease.

Sandip Mhaske

I’m a software developer exploring the depths of .NET, AWS, Angular, React, and digital entrepreneurship. Here, I decode complex problems, share insightful solutions, and navigate the evolving landscape of tech and finance.

Post a Comment

Previous Post Next Post