Search code examples
c#angulartypescriptasp.net-coreconceptual

How to pass database data from C# .NET Core backend to Typescript Angular frontend?


I have created an ASP.NET Core web application with an Angular frontend, via the Visual Studio create new project function. I have also created a SQL Server instance.

I am able to get data in my C# code from the database into a datatype via a getData() method, and I have created a matching datatype in Angular and have created sample data to populate it. I have html pages to show this sample data in a chart. However, what I am struggling with is how to call my C# method to get my database data.

From my research, I can't just call my getData() C# method from js/Angular. I assume the process is Angular typescript code sends an http request to the server, the server calls C# method which gets the database data and then the server sends it back to Angular.

What I am confused on is what exactly is Angular sending the code to and how does the C# getData() method get called, other than just by the general idea of "the server"?

Thank you for your help and time.


Solution

  • In scenarios like yours I use a Web Api backend strategy. In your backend you need a controller, that handles the request your frontend (angular) is sending and sends back data.

    namespace yourproject.Controllers
    {
        [Route("api/[controller]/[action]")]
        [ApiController]
        public class backendController : ControllerBase
        {            
        [HttpGet]
            public ActionResult<IQueryable<yourType>> GetData()
            {
              List<yourType> data = your getdata-Method in the backend
              return new ActionResult<IQueryable<yourType>>(result.AsQueryable());
                
            }
        }
    }
    

    In Angular you can now "consume" this Web API endpoint to get your data. Add HttpClient in your constructor of your ts-file:

      constructor(private http: HttpClient)
    

    and use the generic get method of it to get your data:

     this.http.get<yourType[]>(url + '/GetData/')
        .subscribe(data => this.yourDataInAngular = data)
    

    There are some more things you need to do to get the web api running, but this would be way to much for this answer. Here's the microsoft tutorial for it: Create a web api with ASP.net core