How to Run API and setup API calls on a "Angular and ASP.Net core" Projects

sathya 0 Reputation points
2024-01-26T18:17:43.0033333+00:00

How to Run API and setup API calls on a "Angular and ASP.Net core" Projects.

It would be great if I can get a step by step documentation on how to call the server (ASP.Net core) from the Angular when they in the same project . In my case my project Template is a Angular and ASP.Net core.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,400 questions
Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
4,888 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Zhi Lv - MSFT 32,106 Reputation points Microsoft Vendor
    2024-01-29T08:06:27.3266667+00:00

    Hi @sathya

    With reference to this article: Create an ASP.NET Core app with Angular in Visual Studio, after creating an Angular application using the "Angular and ASP.Net Core" and select the "Use controllers" option, it will create two projects: YourProjectName.client (Angular application) and YourProjectName.Server (API application).

    User's image

    The project structure like this:

    User's image

    After unchecking the Launch Browser option for the profile named after the ASP.NET Core project (or https, if present) (Right-click the AngularWithASP.Server project and choose Properties, in the Properties page, open the Debug tab and select Open debug launch profiles UI option. Uncheck the Launch Browser option)

    Then, Press F5 or select the Start button at the top of the window to start the app. The angular application can work well and show the weather forecast list.

    By default, it already configured the startup projects, like this: the Server (API) application will start before the angular application.

    User's image

    Then to add your custom API and call it from the Angular application, you can refer to the following steps:

    1.In the server project, add a ToDoController in the controller folder:

    namespace MyAngularApp1.Server.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        public class ToDoController : ControllerBase
        {
            // GET: api/<ToDoController>
            [HttpGet]
            public List<Blog> Get()
            {
                var itemlist = new List<Blog>();
    
                for(var i = 0; i < 5; i++)
                {
                    var item = new Blog() { Id=i, Name="Item "+i.ToString(), Description="This is item "+i.ToString() };
                    itemlist.Add(item);                
                };
    
                return itemlist;
            } 
        }
    }
    
    

    2.In the client project proxy.conf.js file, add the proxy for the ToDoController,

    const PROXY_CONFIG = [
      {
        context: [
          "/weatherforecast",
          "/api/todo",
        ],
        target: "https://localhost:7163",
        secure: false
      }
    ]
    
    module.exports = PROXY_CONFIG;
    
    

    in the component (app.component.ts): import the HttpClient, and in the OnInit method, you can call the API controller to get data:

    import { HttpClient } from '@angular/common/http';
    import { Component, OnInit } from '@angular/core'; 
    interface WeatherForecast {
      date: string;
      temperatureC: number;
      temperatureF: number;
      summary: string;
    } 
    interface Blog {
      id: number;
      name: string;
      description: string; 
    } 
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrl: './app.component.css'
    })
    export class AppComponent implements OnInit {
      public forecasts: WeatherForecast[] = [];
      public blogs: Blog[] = [];
      constructor(private http: HttpClient) {}
    
      ngOnInit() {
        this.getBlogs();
        this.getForecasts();
      }
    
      getForecasts() {
        this.http.get<WeatherForecast[]>('/weatherforecast').subscribe(
          (result) => {
            this.forecasts = result;
          },
          (error) => {
            console.error(error);
          }
        );
      }
      getBlogs() {
        this.http.get<Blog[]>('/api/todo').subscribe(
          (result) => {
            this.blogs = result;
          },
          (error) => {
            console.error(error);
          }
        );
      }
      title = 'myangularapp1.client';
    }
    
    

    After that, you can display the result in the html page (app.component.html):

    <h1 id="tableLabel">Weather forecast</h1>
    
    <p>This component demonstrates fetching data from the server.</p>
    
    <p *ngIf="!forecasts"><em>Loading... Please refresh once the ASP.NET backend has started. See <a href="https://aka.ms/jspsintegrationangular">https://aka.ms/jspsintegrationangular</a> for more details.</em></p>
    
    <table *ngIf="forecasts">
      <thead>
        <tr>
          <th>Date</th>
          <th>Temp. (C)</th>
          <th>Temp. (F)</th>
          <th>Summary</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let forecast of forecasts">
          <td>{{ forecast.date }}</td>
          <td>{{ forecast.temperatureC }}</td>
          <td>{{ forecast.temperatureF }}</td>
          <td>{{ forecast.summary }}</td>
        </tr>
      </tbody>
    </table>
    
    <table *ngIf="blogs">
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Description</th> 
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let blog of blogs">
          <td>{{ blog.id }}</td>
          <td>{{ blog.name }}</td>
          <td>{{ blog.description }}</td> 
        </tr>
      </tbody>
    </table>
    
    
    

    The result as below:

    User's image


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
    Best regards,
    Dillion

    0 comments No comments