This page looks best with JavaScript enabled

Single Page Application using Asp.Net Core 2.2 and Angular

 ·  ☕ 6 min read  ·  ✍️ Adesh

Download

Download the .Net Core 2.2 SDK from below link, if you don’t have in your machine.

Download the .Net Core 2.2 SDK -  Mac OS x64 Installer

Run

Run the downloaded Installer

Net Core SDK Installer

Net Core SDK Installer

Net Core SDK Installer

Net Core SDK Installer

Finish Installation

After all these steps, this setup has installed Microsoft .Net Core SDK 2.2 successfully on your MacOS. The following packages have been installed on your MacOS with this installer.

  • .Net Core SDK 2.2.101

  • .Net Core Runtime 2.2.0

  • Asp.Net Core Runtime 2.2.0

Verify Installation

Check the Installation by running these commands in your terminal window.

1
dotnet

Or

1
dotnet --version

Let’s create our Angular app in .Net Core 2.2. We are going to use Visual Studio Core on MacOS. If you don’t have Visual Studio Core, you can download from below link.

Download Visual Studio Core

Create Angular App

Moving forward, let’s create our Angular app using the below command in terminal window. I have created a  AngularDemo directory, and run the command inside this directory.

1
cd angulardemo
1
dotnet new angular -o zeptoapp

After running this command, it will create Visual studio .csproj file in your folder.

Visual Studio Project

Open the Visual Studio Core IDE, and open the zeptoapp folder. It looks like this.

asp.net core solution folder

This project template create an ASP.NET Core app and Angular app. You can use ASP.NET Core app for data access, authorization, and other server-side functionalities.

Your Angular App is inside the ClientApp folder.

Client App folder in .csproj

Run Angular app

Now, go to clientapp->src folder, and try to run your Angular app by this command in terminal.

1
ng serve --open

Note:- If you see this error message in your console.

Could not find module “@angular-devkit/build-angular” from “/Users/XXX/Documents/AngularDemo/zeptoapp/ClientApp”.
Error: Could not find module “@angular-devkit/build-angular” from “/Users/XXX/Documents/AngularDemo/zeptoapp/ClientApp”.
at Object.resolve (/usr/local/lib/node_modules/@angular/cli/node_modules/@angular-devkit/core/node/resolve.js:141:11)
at Observable.rxjs_1.Observable
as _subscribe_
at Observable._trySubscribe (/usr/local/lib/node_modules/@angular/cli/node_modules/rxjs/internal/Observable.js:44:25)
at Observable.subscribe (/usr/local/lib/node_modules/@angular/cli/node_modules/rxjs/internal/Observable.js:30:22)
at /usr/local/lib/node_modules/@angular/cli/node_modules/rxjs/internal/Observable.js:99:19
at new Promise ()
at Observable.toPromise (/usr/local/lib/node_modules/@angular/cli/node_modules/rxjs/internal/Observable.js:97:16)
at ServeCommand.initialize (/usr/local/lib/node_modules/@angular/cli/models/architect-command.js:91:94)
at
at process._tickCallback (internal/process/next_tick.js:188:7)_

Run this npm command in your terminal.

1
npm install --save-dev @angular-devkit/build-angular

Once this @angular-devkit has been installed in your project folder, you are now good to go. Now, run your Angular app using

1
ng serve --open

Running your angular app using ng serve

This will successfully launch Angular app at http://localhost:4200/

Angular app in browser

Run Asp.net Core api with Angular app

Run the complete project. Go to Debug->Start Debugging or Pressing F5, your Angular app and .Net Core app will run altogether.

Home screen

Home Screen

Counter Screen

Counter Screen

Fetch Data

Fetch Data Screen

If you look at the Fetch Data screen, you will be wondering how this data is coming, as we haven’t created any Angular component or service to display the data. This is the magic of .Net Core with Angular. We got everything setup for us. Let’s look into the details of each section.

Let’s first look at out .Net Core Controller API code.

SampleDataController file

SampleDataController.cs

You can see, our have SampleDataController.cs file in Controllers folder of our project. In the controller file, we have code for our Fetch Data page.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace zeptoapp.Controllers
{
    [Route("api/[controller]")]
    public class SampleDataController : Controller
    {
        private static string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        [HttpGet("[action]")]
        public IEnumerable<WeatherForecast> WeatherForecasts()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                DateFormatted = DateTime.Now.AddDays(index).ToString("d"),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            });
        }

        public class WeatherForecast
        {
            public string DateFormatted { get; set; }
            public int TemperatureC { get; set; }
            public string Summary { get; set; }

            public int TemperatureF
            {
                get
                {
                    return 32 + (int)(TemperatureC / 0.5556);
                }
            }
        }
    }
}

Now, look at the Angular component in our project solution.

fetch-data.component

fetch-data component

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import { Component, Inject } from "@angular/core";
import { HttpClient } from "@angular/common/http";

@Component({
  selector: "app-fetch-data",
  templateUrl: "./fetch-data.component.html",
})
export class FetchDataComponent {
  public forecasts: WeatherForecast[];

  constructor(http: HttpClient, @Inject("BASE_URL") baseUrl: string) {
    http
      .get<WeatherForecast[]>(baseUrl + "api/SampleData/WeatherForecasts")
      .subscribe(
        (result) => {
          this.forecasts = result;
        },
        (error) => console.error(error)
      );
  }
}

interface WeatherForecast {
  dateFormatted: string;
  temperatureC: number;
  temperatureF: number;
  summary: string;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<h1>Weather forecast</h1>

<p>This component demonstrates fetching data from the server.</p>

<p *ngIf="!forecasts"><em>Loading...</em></p>

<table class="table table-striped" *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.dateFormatted }}</td>
      <td>{{ forecast.temperatureC }}</td>
      <td>{{ forecast.temperatureF }}</td>
      <td>{{ forecast.summary }}</td>
    </tr>
  </tbody>
</table>

Run Angular app Independently

The project is configured to start its own instance of the Angular CLI server in the background when the ASP.NET Core app starts in development mode. This is convenient because you don’t have to run a separate server manually.

There’s a drawback to this default setup. Each time you modify your C# code and your ASP.NET Core app needs to restart, the Angular CLI server restarts. Around 10 seconds is required to start back up. If you’re making frequent C# code edits and don’t want to wait for Angular CLI to restart, run the Angular CLI server externally, independently of the ASP.NET Core process. To do so:

  • In terminal, go to ClientApp folder, and run this command.
1
npm start
  • Modify your ASP.NET Core app to use the external Angular CLI instance instead of launching one of its own. In your Startup class, replace the spa.UseAngularCliServer invocation with the following:

When you start your ASP.NET Core app, it won’t launch an Angular CLI server. The instance you started manually is used instead. This enables it to start and restart faster. It’s no longer waiting for Angular CLI to rebuild your client app each time.

Summary

In summary, we have learned how to create a single page application using Asp.Net core as backend and Angular as frontend. This is more productive, flexible and less time consuming process.

Further reading

Pipes in Angular

Share data between components in Angular

Fresh releases of Visual Studio 2017 for Mac and TypeScript 3.2

Share on

Adesh
WRITTEN BY
Adesh
Technical Architect