Skip to content

Instantly share code, notes, and snippets.

@DevEarley
Last active March 26, 2023 23:40
Show Gist options
  • Save DevEarley/5e0d552ce1d1847d621a24f8911b9314 to your computer and use it in GitHub Desktop.
Save DevEarley/5e0d552ce1d1847d621a24f8911b9314 to your computer and use it in GitHub Desktop.
.NET Core WebAPI and Angular Quick Start Guide

.NET Core WebAPI and Angular Quick Start Guide

Why Angular and .NET Core?

Angular is a well established frontend framework. With Angular, you can quickly bind input fields to logic that calls the .NET Core WebAPI backend. WebAPI is simple to set up and can host our angular app without MVC.

Installation

  • Download VS Code
  • Download .NET Core CLI for your OS.
  • Download Node.JS
  • Open up your favorite command prompt. (I use Bash from the VS Code terminal)
npm i -g @angular/cli

If you are on MacOS - please see this guide : Setup Angular CLI & .NET Core on MacOS

Setup Angular and .NET Core WebAPI

Now that everything is installed, you need to setup some boilerplate code. This code will help you get your app started. Run the following commands in your command prompt. Start by making a project directory for the .NET project.

mkdir my-project-server
cd my-project-server

Next, initialize the project.

dotnet new webapi

Go to the directory and open it in Visual Studio Code ( you can do this by right clicking in the root and choosing 'Open with Code'. Open the Startup.cs file and replace the contents with the following.

  ...
namespace my_project
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }
        public void Configure(IApplicationBuilder app)
        {
            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseHttpsRedirection();           
        }
  ...

This tells .NET to host whatever static files are in the wwwroot folder and to not use MVC. ( you don't need MVC, you are using Angular!) Now our very basic backend is set up, next is Angular. Back to the command prompt. (If you are using VS Code, use the terminal!) Navigate up to the root of your repository.

cd ../

Now Init Angular. This time, Angular will create its own directory

ng new my-project
cd my-project

Once Angular is built, it will build files and put them into the dist folder. The WebAPI is serving static files from the wwwroot folder. We need to configure Angular to output to this folder.

Open the angular.json file and find the property called outputPath, change it to "../my-project-server/wwwroot".

      ...
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "../my-project-server/wwwroot",
      ...

Now build angular and run the .NET server application

ng build
cd ../my-project-server
dotnet build
dotnet run

To view, navigate to https://localhost:5001/ in your browser.

Get data from the API into Angular

Create the API service in Angular. This is what our component will use to communicate with the API.

ng generate service my-api

Next up, Import the HttpClient into the Angular Module. Open up the app.module.ts in VS Code. Import the HttpClientModule at the top, and add to the list of imports in the NGModule decorator. And make sure to add the API service to the list of providers.

import {HttpClientModule} from '@angular/common/http';
import { MyApiService } from './my-api.service';

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        HttpClientModule
    ],
    providers: [MyApiService],
    bootstrap: [AppComponent]
})
export class AppModule {
}

Open the API service file up in VS code and import HttpClient and inject it through the constructor. Also import Observable, you will need that soon.

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class MyApiService {
  constructor(private httpClient:HttpClient) { }
}

Just below the constructor, add a get method that returns a promise. Also add a base URL to this service class.

export class MyApiService { 
 baseUrl = "api";
  constructor(private httpClient: HttpClient) { }  
  
   get(): Promise<any> {
    var httpGet$: Observable<any> = this.httpClient.get(this.baseUrl);
    return httpGet$.toPromise();
  }
}

Open up App.Component.ts and inject this service into the constructor.

...
import { MyApiService } from './services/my-api.service';
...
 constructor(private api:MyApiService) {
    super(layer);  
    this.api.get().then(result => { ... }, error => { ... });
  }
  
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment