Seamlessly Integrate .NET Core API with Angular

Accessing a .NET Core API method in an Angular application involves several steps, including setting up the API, creating the Angular service to call the API, and using the service in your Angular components. Here's a step-by-step guide.

Step 1. Set Up the .NET Core API

  1. Create a New .NET Core API Project.
    • Open Visual Studio or Visual Studio Code.
    • Create a new project by selecting "ASP.NET Core Web API".
    • Choose the project template and configure it as needed.
  2. Define a Controller.
    • In the Controllers folder, create a new controller, e.g., WeatherController.cs.
      using Microsoft.AspNetCore.Mvc;
      
      namespace YourNamespace.Controllers
      {
          [Route("api/[controller]")]
          [ApiController]
          public class WeatherController : ControllerBase
          {
              [HttpGet]
              public IActionResult GetWeather()
              {
                  var weatherData = new { Temperature = 25, Condition = "Sunny" };
                  return Ok(weatherData);
              }
          }
      }
      
  3. Run the API.
    • Start the API by running the project. The API will typically run on http://localhost:5000 or https://localhost:5001.

Step 2. Set Up the Angular Application

  1. Create a New Angular Project.
    • Open a terminal or command prompt.
    • Use the Angular CLI to create a new project: "ng new my-angular-app"
    • Navigate to the project directory: "cd my-angular-app"
  2. Install HttpClient Module.
    • Ensure HttpClientModule is installed and imported into your Angular application.
    • Open src/app/app.module.ts and add HttpClientModule to the imports array.
      import { BrowserModule } from '@angular/platform-browser';
      import { NgModule } from '@angular/core';
      import { AppComponent } from './app.component';
      import { HttpClientModule } from '@angular/common/http';
      
      @NgModule({
        declarations: [
          AppComponent
        ],
        imports: [
          BrowserModule,
          HttpClientModule
        ],
        providers: [],
        bootstrap: [AppComponent]
      })
      export class AppModule { }
      

Step 3. Create a Service to Call the API

  1. Generate a New Service.
    • Use the Angular CLI to generate a new service: "ng generate service weather"
  2. Define the Service.
    • Open src/app/weather.service.ts and add the following code.
      import { Injectable } from '@angular/core';
      import { HttpClient } from '@angular/common/http';
      import { Observable } from 'rxjs';
      
      @Injectable({
        providedIn: 'root'
      })
      export class WeatherService {
        private apiUrl = 'https://localhost:5001/api/weather'; // Adjust the URL as necessary
      
        constructor(private http: HttpClient) { }
      
        getWeather(): Observable<any> {
          return this.http.get<any>(this.apiUrl);
        }
      }
      

Step 4. Use the Service in a Component

  1. Generate a New Component.
    • Use the Angular CLI to generate a new component: "ng generate component weather"
  2. Inject and Use the Service.
    • Open src/app/weather/weather.component.ts and modify it to use the service.
      import { Component, OnInit } from '@angular/core';
      import { WeatherService } from '../weather.service';
      
      @Component({
        selector: 'app-weather',
        templateUrl: './weather.component.html',
        styleUrls: ['./weather.component.css']
      })
      export class WeatherComponent implements OnInit {
        weather: any;
      
        constructor(private weatherService: WeatherService) { }
      
        ngOnInit(): void {
          this.weatherService.getWeather().subscribe(data => {
            this.weather = data;
          });
        }
      }
      
  3. Update the Template.
    • Open src/app/weather/weather.component.html and add the template.
      <div *ngIf="weather">
        <p>Temperature: {{ weather.Temperature }}°C</p>
        <p>Condition: {{ weather.Condition }}</p>
      </div>
      

Step 5. Integrate the Component

  1. Update the App Component.
    • Open src/app/app.component.html and use the new component.
      <app-weather></app-weather>
      

Step 6. Run the Angular Application

  1. Start the Angular Application.
    • Run "ng serve" in the terminal.
    • Open a web browser and navigate to http://localhost:4200.

By following these steps, your Angular application will successfully call and display data from the .NET Core API method.


Similar Articles