What is the best way to pass a data array from angular to web API C#
Loading
What is the best way to pass a data array from angular to web API C#
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Sangeetha SPosted Nov 15, 2024, 6:51 AM
Passing a data array from an Angular application to a C#
Angular code
import { HttpClient } from '@angular\/common\/http';
import { Injectable } from '@angular\/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
private apiUrl = 'https:\/\/yourapiurl.com\/api\/data';
constructor(private http: HttpClient) {}
sendData(dataArray: any[]) {
return this.http.post(this.apiUrl, dataArray);
}
}
Component
import { Component } from '@angular\/core';
import { DataService } from '.
@Component({
selector: 'app-your-component',
templateUrl: '.\/your-component.component.html',
})
export class YourComponent {
constructor(private dataService: DataService) {}
submitData() {
const myDataArray = [1, 2, 3, 4];
this.dataService.sendData(myDataArray).subscribe(response => {
console.log('Data sent successfully', response);
}, error => {
console.error('Error sending data', error);
});
}
}
Web api
[ApiController]
[Route("api/[controller]")]
public class DataController : ControllerBase
{
[HttpPost]
public IActionResult ReceiveData([FromBody] int[] dataArray)
{
return Ok(new { message = "Data received successfully", receivedData = dataArray });
}
}
Jayraj ChhayaPosted Nov 15, 2024, 6:52 AM
To pass a data array from Angular to a C# Web API, you can utilize the
HttpClientservice in Angular to send a POST request containing the array. The C# Web API can then receive this data as a parameter in the action method.Angular Code
C# Web API Code
The Angular service sends a data array to the specified API endpoint, and the C# Web API method processes the incoming data. Ensure that the API is configured to accept JSON data, which is the default behavior when using
[FromBody].