Contents
Nowadays, gone are the frameworks with monolithic approach. Latest frameworks tend to be more modular. ASP.Net Core is a re-write of ASP.Net but a lot more modular same with Angular 4 (2) from AngularJS.
These modern frameworks offers CLI (Command Line Interface) Tools that give developers more option in developing next generation applications. CLI tools give developers the freedom to work from any operating system. It is evident that GUI tools do not work on all major operating systems. Best example of this is Visual Studio which works only on Windows and just recently on Mac.
One of the ways to create an SPA (Single Page Application) project made of Angular and ASP.NET Core Web API is to use Visual Studio Template. Although this approach is convenient, you are dependent with the template which is created and being updated by some individuals who may not be even part of the framework developers.
This tutorial is a starter guide for developers who heard and became curious about the increasing popularity of Angular and ASP.NET Core but do not know how to start.
- How to create an Angular project using Angular CLI
- How to create an ASP.Net Core Wep API using Dotnet Core CLI
- How to integrate both of these projects
- How to install, update and use latest CLIs
This tutorial is for Microsoft Windows but it can be used as guide for other operating systems except for the installation part.
- Microsoft Windows 10 Version 1703, 64 bit (created on this version)
Here are the key steps to take:
- Download and install SDKs
- Download and install Visual Studio Code
- Update npm
- Install Angular CLI
- Check versions
- Create Angular project (this is where real work begins)
- Create ASP.Net Core Web API project
- Integrate projects
Please note that installation processes are different on every operating system. Step-by-step installation of SDK is not covered in this tutorial. The screenshots are the first window after executing the installer for Windows.
Download and install SDKs:
- .NET Core 2.0 SDK
- Node.js SDK
Download .NET Core 2.0 SDK installer.
Install the downloaded installer.
Download Node.js SDK installer.
Download Current for latest features.
Install the downloaded installer.
Use Microsoft Visual Studio Code (VS Code) as GUI tool, IDE (Integrated Development Environment) for development.
Download Microsoft Visual Studio Code installer.
Install. Install the downloaded installer.
Node.js installer installs npm by default but it maybe not the latest.
Update npm from command line as Administrator. Follow the guide here on how to run command line (cmd.exe) as Administrator.
Do not close the command line for it will be used on succeeding steps.
Explanation:
cd\
- change Directory from current path to the root path. In the screenshots above, C: is the root path.
npm update -g npm
- update the globally (-g) installed Node Package Manager (NPM)
Install angular cli from command line.
Explanation:
npm install -g @angular/cli
- using npm, angular cli is installed globally.
At this point, check versions of SDK/CLI installed.
Explanation:
dotnet --version
- displays .NET Core SDK version
node -v
- displays Node.js version
npm -v
- displays NPM version
ng -v
- displays Angular CLI version
Create an Angular project using Angular (ng) CLI.
Explanation:
cd projects
- change current path to "projects" folder under the current path. This is to organize projects into one folder
ng new hello-world
- using Angular (ng) CLI, create a folder "hello-world" under the current path and add new angular project with same name
- issuing "ng new hello-word & cd new hello-world" from command line will immediately change the current path to "hello-world" after creating the project
Run the newly created Angular project.
Explanation:
cd hello-world
- change current path to "hello-world" folder under the current path
ng server --open
- "ng serve" builds the application and starts a web server
- "--open" opens web browser after successful build and web server is started. For other options, refer here. Without using "--open" option, you can see the output by opening web browser on "http://localhost:4200" as url.
Created web page will be displayed in the web browser.
Terminate the web server by issuing "ctrt + c", then press "Y" then "Enter".
Although the succeeding processes can still be executed using command line, VS Code will be used this time. In fact, all Angular commands previously done in command line can also be executed inside VS Code. I prefer working inside VS Code to prevent switching between opened windows.
Open the project in VS Code using command line (1st Way)
Explanation:
code .
- open the current folder in VS Code
Open project in VS Code (2nd Way)
After running VS Code, select the project folder by clicking "File-Open Folder..." from menu.
Show integrated terminal (command line) in VS Code by clicking "View-Integrated Terminal" from menu or "Ctrl + ~" as keyboard shortcut. This explains why everything can be executed inside VS Code.
From the terminal (integrated command line), create new ASP.NET Core Web API project.
Explanation:
dotnet new webapi
- using DotNet CLI, create a new Web API project. Without specifying options, Dotnet CLI will create a project with name equals to the folder where "new" command is issued. For additional information, refer to this link.
Select "Yes" and "Restore" on the messages displayed by VS Code. Settings will be added to enable debugging after clicking "Yes". Just note that debugging is included topic in this tutorial so it doesn't matter whatever option you opt to select. Clicking "Restore" will restore dependies or libraries needed for ASP.NET Core Web API.
Notice in Side Bar "hello-world.csproj" has been added. That's the newly added ASP.NET Core Web API project. If Side Bar is not displayed, click "View-Toggle Side Bar" from menu to show/hide it or "Ctrl + B" if you prefer keyboard shortcut.
At this point, two projects exists: the existing Angular project and the newly added ASP.NET Core Web API project. Although the projects are on the same folder, it has no relation right now.
Build and run the newly created ASP.NET Core Web API project.
Open web browser on "http://localhost:5000/api/values" as url. Be sure to add "/api/values" to the url because that's the default route for the newly created Web API.
Terminate the web server by pressing "Ctrl + C" at the integrated terminal.
Open ".angular-cli.json" and change "outDir" under "apps" to "wwwroot". This tells Angular CLI to save the compilation output files to the same folder where DotNet CLI is outputting.
Delete "ValuesController.cs" from "Controllers" folder and replacing it with a simple Web API that just returns a simple "hello" greetings.
Create "HelloController.cs" inside "Controllers" folder. Right click on "Controllers" folder and click "New File". Name the file to "HelloContoller.cs".
Paste the code below.
[Controllers\HelloController.cs]
using System;
using Microsoft.AspNetCore.Mvc;
namespace hello_world
{
[Route("api/[Controller]")]
public class HelloController : Controller
{
[HttpGet]
public IActionResult Greetings() {
return Ok("Hello from ASP.NET Core Web API.");
}
}
}
Modify Startup.cs to include "UseDefaultFiles" and "UseStaticFiles" in the HTTP request pipeline.
With "UseDefaultFiles", requests to a folder will search for:
- default.htm
- default.html
- index.htm
- index.html
"UseStaticFiles" makes the files in web root (wwwroot by default) servable.
For additional information regarding UseDefaultFiles" and "UseStaticFiles", refer to this link.
At this timing, our work on Web API project is completed. Let's go back to Angular and consume Web API from Angular.
Create a new file "app.service.ts" inside "src\app" folder and paste the code below.
[src\app\app.service.ts]
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class AppService {
private greetUrl = 'api/Hello';
constructor(private _http: Http) { }
sayHello(): Observable<any> {
return this._http.get(this.greetUrl).map((response: Response) => {
return response.text();
});
}
}
Modify "app.module.ts" and add "AppService" as providers. Then import "HttpModule".
[src\app\app.module.ts]
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { AppService } from './app.service';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpModule
],
providers: [AppService],
bootstrap: [AppComponent]
})
export class AppModule { }
Modify "app.component.ts" to inject "AppService".
[src\app\app.component.ts]
import { Component, OnInit } from '@angular/core';
import { Http, Response } from '@angular/http';
import { AppService } from './app.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
greetings = '';
constructor(private _appService: AppService) { }
ngOnInit(): void {
this._appService.sayHello()
.subscribe(
result => {
this.greetings = result;
}
);
}
}
Change the contents of "app.component.html".
[src\app\app.component.html]
<h2 class='panel-heading'>
{{greetings}}
</h2>
<hr/>
Build Angular.
Build DotNet.
Run DotNet.
Open web browser to "http://localhost:5000/". Notice that "api/*" is not included in the url. When page is loaded, Angular is loaded first then web api is consumed inside Angular thus showing the greetings.
That's it.
We already learned how to create Angular and DotNet projects using each respective CLI. We were also able to integrate the two projects. This means we are now capable of using the best out of CLI of two completely different framework. So, what's next?
1. Learn ASP.Net Core Web API from here.
2. Learn Angular from here.
09/16/2017 - Initial creation
09/17/2017 - Fixed broken images