Example 1/5: Using Angular 17 with ASP.Net Core API to Make API Calls and Display Data Using C#

Posted by

Angular 17 with ASP.Net Core API Examples

Angular 17 with ASP.Net Core API Examples

In this article, we will explore how to use Angular 17 with ASP.Net Core API to fetch and display data.

Example 1: API Call to fetch and display data (C#)

First, let’s create an Angular 17 application that makes an API call to fetch and display data from an ASP.Net Core API.

// app.component.ts

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  data: any;

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.http.get('https://example.com/api/data').subscribe((response) => {
      this.data = response;
    });
  }
}

In the above example, we have created a simple Angular component that uses the HttpClient to make an API call to fetch data from the ASP.Net Core API. The fetched data is then assigned to the ‘data’ property of the component.

Now, let’s create the ASP.Net Core API that will provide the data to be fetched by the Angular application.

// ValuesController.cs

using Microsoft.AspNetCore.Mvc;

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        var data = new string[] { "value1", "value2", "value3" };
        return Ok(data);
    }
}

The above code snippet shows a simple ASP.Net Core API controller that returns an array of strings as the data to be fetched by the Angular application.

With the above setup, when the Angular application is run, it will make an API call to the ASP.Net Core API and fetch the data, which will then be displayed to the user.

This is just the first example of how Angular 17 can be used with ASP.Net Core API to fetch and display data. In the next example, we will explore how to handle data in a more complex scenario.