How can we connect Angular project to ASP.Net Web API?

Here is an example of how to connect an Angular application to a .NET Web API:

  1. Create a new .NET Web API project:

    • Open Visual Studio and create a new ASP.NET Web Application.
    • Choose the "Web API" template and click "Create."
  2. Create a data model:

    • Define a data model for the API using C# classes. For example:
    csharp
    public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } public DateTime CreatedAt { get; set; } }
  3. Create a controller:

    • Add a new controller class to the project to handle API requests. For example:

    csharp
    [Route("api/products")] public class ProductsController : ApiController { private readonly List<Product> _products = new List<Product>() { new Product { Id = 1, Name = "Product 1", Price = 9.99m, CreatedAt = DateTime.Now.AddDays(-7) }, new Product { Id = 2, Name = "Product 2", Price = 19.99m, CreatedAt = DateTime.Now.AddDays(-3) }, new Product { Id = 3, Name = "Product 3", Price = 29.99m, CreatedAt = DateTime.Now.AddDays(-1) }, }; [HttpGet] public IHttpActionResult GetAllProducts() { return Ok(_products); } }
  4. Enable CORS:

    • Enable Cross-Origin Resource Sharing (CORS) to allow the Angular application to access the API. Add the Microsoft.AspNet.WebApi.Cors NuGet package to the project, and configure the WebApiConfig.cs file to enable CORS for the desired domains. For example:

  5. csharp
    public static void Register(HttpConfiguration config) { // Enable CORS for all origins and headers var cors = new EnableCorsAttribute("*", "*", "*"); config.EnableCors(cors); // Web API routes config.MapHttpAttributeRoutes(); // Other configuration... }
  6. Test the API:

    • Run the API project in Visual Studio and test the API endpoints using a tool like Postman.
  7. Create an Angular application:

    • Create a new Angular project using the Angular CLI. For example:
  8. arduino
    ng new my-app
  9. Integrate the API with the Angular application:

    • Create a service in the Angular application to encapsulate the HTTP requests to the API. For example:
    typescript
    import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { Product } from './product'; @Injectable({ providedIn: 'root' }) export class ProductService { private apiUrl = 'http://localhost:1234/api/products'; constructor(private http: HttpClient) { } getProducts(): Observable<Product[]> { return this.http.get<Product[]>(this.apiUrl); } }

    • Inject the service into the components that need to use the API. For example:

    typescript
    import { Component, OnInit } from '@angular/core'; import { ProductService } from '../product.service'; import { Product } from '../product'; @Component({ selector: 'app-product-list', templateUrl: './product-list.component.html', styleUrls: ['./product-list.component.css'] }) export class ProductListComponent implements OnInit { products: Product[]; constructor(private productService: ProductService) { } ngOnInit(): void { this.getProducts(); } getProducts(): void { this.productService.getProducts().subscribe(products => this.products = products); } }
  10. In this component, we inject the ProductService into the constructor using Angular's dependency injection mechanism. We also implement the OnInit lifecycle hook, which is called when the component is initialized. In the ngOnInit method, we call the getProducts method to fetch the products from the API using the ProductService. When the response is returned, we assign the products to the products property of the component. Finally, we define the getProducts method to make the HTTP request to the API using the ProductService and subscribe to the response to get the products.

Comments

Popular posts from this blog

Mastering IIFEs in TypeScript: Encapsulate Your Code Like a Pro

How can we implement lazy loading in angular explain with example?

Creating and Testing an Angular Library for Form Validation