Click here to Skip to main content
15,891,607 members
Articles / Web Development / ASP.NET / ASP.NET Core
Tip/Trick

Working with Angular/Cli + ASP.NET Core Web API + VSCode !

Rate me:
Please Sign up or sign in to vote.
3.40/5 (7 votes)
19 Mar 2018CPOL2 min read 35.4K   10   5
Simple steps to integrate Angular Cli and ASP.NET core web API using VS Code

This sample is meant as a starting step to create a standard ASP.NET Web API project using dotnet Cli command and integrate with the Angular library with the help of @Angular/CLI command to make use of all the cli features.

 
Recently Microsoft introduced AngularCLI integration - https://docs.microsoft.com/en-us/aspnet/core/spa/angular?tabs=visual-studio 

Step 1: Install NodeJs

Step 2: Install @Angular/Cli

  • Download and install @Angular/Cli using npm install -g @angular/cli

Step 3: Install Visual Studio Code

Step 4: Create @Angular/Cli Command Line Project

  • Open Visual Studio Code
  • #File -> Open Folder (select/ create folder)
  • Navigate to #View-> Integrated Terminal
  • Create Angular project template :> ng new projectName (e.g., ng new AngularAspnetWebapi)
  • Navigate to project folder #File -> Open Folder -> new directory path (e.g. AngularAspnetWebapi)

Step 5: Create VSCode dotnet cli ASP.NET Web API Project :

  • Your @ new directory (e.g. AngularAspnetWebapi)
  • Navigate to #View-> Integrated Terminal
  • Create dotnet web API project :> dotnet new webapi - This command will create web API project at selected folder location
  • Run npm install (this will take some time to download npm packages)
  • Don't build the project (It's better to compile and launch application using - launch.json and tasks.json)

Step 6: Change config File - Link Web API and Angular CLI Output

  • Navigate & open .angular-cli.json file
  • Modify output directory path - "outDir":"dist" to "outDir": "wwwroot"
    JavaScript
    // Original/Old config file
    {
      "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
      "project": {
        "name": " AngularAspnetWebapi "
      },
      "apps": [
        {
          "root": "src",
          "outDir": "dist",
          "assets": [
            "assets",
            "favicon.ico"
          ],
          ...
    
    JavaScript
    // Updated config file
    {
      "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
      "project": {
        "name": " AngularAspnetWebapi "
      },
      "apps": [
        {
          "root": "src",
          "outDir": "wwwroot",
          "assets": [
            "assets",
            "favicon.ico"
          ],
          ...
    
  • Build Angular project using :>ng build (Angular output at wwwroot folder)

Step 7: Create Angular Component

ASP.NET Web API project will create default controller under Controller folder:

JavaScript
[Route("api/[controller]")]
   public class ValuesController : Controller
   {
       // GET api/values
       [HttpGet]
       public IEnumerable<string> Get()
       {
           return new string[] { "value1", "value2" };
       }

Navigate to Integrated Terminal & execute command :>ng generate component value or :>ng g c value. This command will create a component and update the module for you.

JavaScript
create src/app/value/value.component.html (24 bytes)
create src/app/value/value.component.spec.ts (621 bytes)
create src/app/value/value.component.ts (265 bytes)
create src/app/value/value.component.css (0 bytes)
update src/app/app.module.ts (394 bytes)

Access web API (communicate angular and ASP.NET web API).

JavaScript
 // Default generated code - valueComponent 
 import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-value',
  templateUrl: './value.component.html',
  styleUrls: ['./value.component.css']
})
export class ValueComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }
}

Update value.component.ts file with the following:

add Http import --- import { Http  } from '@angular/http';
create new variable values --- value = {};
call web Api  ---  this.http.get(`<api path>`).subscribe
                                ( response => this.value = response.json());
JavaScript
// Updated code 
import { Component, OnInit } from '@angular/core';
import { Http  } from '@angular/http';

@Component({
  selector: 'app-value',
  templateUrl: './value.component.html',
  styleUrls: ['./value.component.css']
})
export class ValueComponent implements OnInit {
  value = {};
  constructor(private http: Http) { }
  
  ngOnInit() {
  }
  getValues() {
      this.http.get(`http://localhost:5000/api/values`).subscribe
                   ( response => this.value = response.json());
    }
}

Update value.component.html with the following:

HTML
// Old code
<p>
  value works!
</p> 
HTML
// New code 
<div>
  <button (click)="getValues()">Load values</button>
  {{ value | json }}
</div>

Step 8: Angular Routing

Setup angular routing for new component goes to app.module.ts file and update the following:

JavaScript
// Old code
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ValueComponent } from './value/value.component';

@NgModule({
  declarations: [
    AppComponent,
    ValueComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
JavaScript
// new code 

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ValueComponent } from './value/value.component';
import { RouterModule, Routes } from '@angular/router';
import { HttpModule } from '@angular/http';

const appRoutes: Routes = [
    {path: '', redirectTo: 'value', pathMatch: 'full' },
    { path: 'value',  component: ValueComponent },
    { path: '**', redirectTo: ''}
  ];

@NgModule({
  declarations: [
    AppComponent,
    ValueComponent
   ],
  imports: [
    BrowserModule,
    HttpModule,
    RouterModule.forRoot(appRoutes)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Update app.component.html file:

HTML
<!--  Old code -->
<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
  <img width="300" alt="Angular Logo" src="data:image/svg+xml;base64,
   PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KI
   CAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw
   3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIy
   LjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRk
   ZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEy
   NSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">
</div>
<h2>Here are some links to help you start: </h2>
<ul>
  <li>
    <h2><a target="_blank" rel="noopener" href="https://angular.io/tutorial">Tour of Heroes</a></h2>
  </li>
  <li>
    <h2><a target="_blank" rel="noopener" href="https://github.com/angular/angular-cli/wiki">
           CLI Documentation</a></h2>
  </li>
  <li>
    <h2><a target="_blank" rel="noopener" href="https://blog.angular.io/">Angular blog</a></h2>
  </li>
</ul>
HTML
<!-- component navigation placeholder -->
<div class='container-fluid'>
  <div class='row'>
     <div class='col-sm-12 body-content'>
          <router-outlet></router-outlet>
      </div>
  </div>
</div>

Step 9: Update startup.cs File

Add UseDefaultFiles (web server looks for default file index.html) and UseStaticFile (web server looks for wwwroot folder) to Startup.cs middleware:

JavaScript
//Old code
 if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseMvc();
JavaScript
//New code

 if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseMvc();

Step 10: Execute and Run Project

There are many ways to configure build configuration. Below is the simplest one:

  1. Compile Angular project using :>ng build
  2. Navigate Debug -> Start debugging

    It will open command palette. Select .NET Core. It will create launch.json and tasks.json or it will open assistance "Required assets to build and debug are missing from"". add them? -- click on Yes.

Click on Load values button will connect to API and fetch value.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Australia Australia
Senior Software Developer working on different Microsoft Technologies.
Desktop applications , Web application , Service layer , Azure

Comments and Discussions

 
Question.angular-cli.json and outDir Pin
moiraphael117-Dec-18 10:40
moiraphael117-Dec-18 10:40 
QuestionBlocked loading mixed active content Pin
moiraphael117-Dec-18 10:38
moiraphael117-Dec-18 10:38 
QuestionRouting Pin
Jack R. Schaible4-Jul-18 18:47
professionalJack R. Schaible4-Jul-18 18:47 
QuestionInstead of VS code how to use VS IDE community edition Pin
Mou_kol15-Mar-18 22:23
Mou_kol15-Mar-18 22:23 
AnswerRe: Instead of VS code how to use VS IDE community edition Pin
MathsInBinaries16-Mar-18 6:50
MathsInBinaries16-Mar-18 6:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.