Example 4/5: Making a POST API Call Using Angular 17, ASP.NET Core Web API (C#), and SQL Server Stored Proc

Posted by

Angular 17 POST API Call ASP.NET Core Web API (C#) and SQL Server Stored Proc | Example 4/5

body {
font-family: Arial, sans-serif;
padding: 20px;
}
h1 {
color: #333;
}
p {
color: #666;
margin-bottom: 20px;
}
code {
background-color: #f4f4f4;
padding: 5px;
border-radius: 4px;
}

Angular 17 POST API Call ASP.NET Core Web API (C#) and SQL Server Stored Proc | Example 4/5

In this tutorial, we will be demonstrating a step-by-step guide on how to make a POST API call using Angular 17 with an ASP.NET Core Web API (C#) back end. We will also be working with a SQL Server stored procedure to handle data manipulation.

Prerequisites

Before we begin, make sure you have the following prerequisites installed:

  • Node.js and npm
  • Angular CLI
  • Visual Studio with ASP.NET Core installed
  • SQL Server Management Studio (SSMS)

Step 1: Create an Angular 17 Project

Open your terminal or command prompt and run the following command to create a new Angular project:


ng new angular-post-api

Once the project is created, navigate into the project directory:


cd angular-post-api

Step 2: Create an ASP.NET Core Web API Project

Open Visual Studio and create a new ASP.NET Core Web API project. You can name it as you like, but for this example, we will name it MyApi.

Create a new controller with a POST endpoint to handle the API call:


[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly MyDbContext _context;
public ValuesController(MyDbContext context)
{
_context = context;
}
[HttpPost]
public async Task PostData([FromBody] MyModel data)
{
// Call SQL Server stored procedure here
return Ok();
}
}

Step 3: Set Up SQL Server Stored Procedure

In SQL Server Management Studio, create a new stored procedure to handle the data manipulation. For example:


CREATE PROCEDURE InsertData
@Param1 NVARCHAR(50),
@Param2 NVARCHAR(50)
AS
INSERT INTO MyTable (Column1, Column2) VALUES (@Param1, @Param2)

Step 4: Make API Call from Angular

In your Angular project, create a new service to make the API call:


import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class DataService {
private apiUrl = 'https://localhost:44386/api/values';
constructor(private http: HttpClient) { }
postData(data: any) {
return this.http.post(this.apiUrl, data);
}
}

Now you can use this DataService in your Angular component to make the API call and handle the response.

Conclusion

By following the steps above, you have successfully created an Angular 17 project that makes a POST API call to an ASP.NET Core Web API. You have also integrated a SQL Server stored procedure to handle the data manipulation. This example demonstrates the end-to-end process of handling data from the front end to the back end and database.