Dotnet (asp.net Core) Web API Http Get Request from Angular App Example
In this article, we will look at an example of making an Http Get request from an Angular app to a Dotnet (asp.net Core) Web API. This is a common scenario in web development, where the front-end Angular app needs to retrieve data from the back-end Web API.
Step 1: Set up the Dotnet Web API
First, let’s create a Dotnet (asp.net Core) Web API to serve as the back-end. This can be done using Visual Studio or the Dotnet CLI. Here’s an example of a simple controller with an Http Get action:
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
private readonly IProductService _productService;
public ProductsController(IProductService productService)
{
_productService = productService;
}
[HttpGet]
public async Task<ActionResult<IEnumerable>> GetProducts()
{
var products = await _productService.GetProducts();
return Ok(products);
}
}
Step 2: Create the Angular App
Next, let’s create an Angular app to make the Http Get request to the Web API. This can be done using the Angular CLI. Here’s an example of a service that makes the Http Get request using Angular’s HttpClient:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Product } from './product.model';
@Injectable({
providedIn: 'root'
})
export class ProductService {
private apiUrl = 'https://localhost:5001/api/products';
constructor(private http: HttpClient) { }
getProducts(): Observable<Product[]> {
return this.http.get<Product[]>(this.apiUrl);
}
}
Step 3: Use the Service in a Component
Finally, we can use the ProductService in an Angular component to fetch and display the data from the Web API. Here’s an example of using the ProductService in an Angular component:
import { Component, OnInit } from '@angular/core';
import { ProductService } from './product.service';
@Component({
selector: 'app-products',
templateUrl: './products.component.html',
styleUrls: ['./products.component.css']
})
export class ProductsComponent implements OnInit {
products: Product[];
constructor(private productService: ProductService) { }
ngOnInit() {
this.productService.getProducts()
.subscribe(products => this.products = products);
}
}
With these simple steps, you can make an Http Get request from an Angular app to a Dotnet (asp.net Core) Web API. This allows you to retrieve data from the back-end and display it in the front-end, providing a seamless user experience.