Wednesday 17 January 2018

ASP .NET Core Application using AngularJS 2

Starting Angular 2 in ASP.NET Core with TypeScript using Visual Studio 2015

This tutorial aims for starting Angular 2 in ASP.NET Core using Visual Studio 2015. 
The release of Angular 2, ASP.NET Core RC is becoming interesting to build SPA.

I have compiled the steps involved in starting to learn Angular 2

Step 1 : Creating an empty ASP.NET Core project Open Visual Studio 2015 Community Edition Update 3.
Select New Web Project naming it “CoreAngular2” and select “Empty” project template. Don’t forget to install new web tools for ASP.NET Core 1.0 




















I used Visual Studio 2015 Community Edition Update 3(Must update), TypeScript 2.0 (must), latest NPM.





















Step 2: Configure ASP.NET Core to serve Static Files ASP.NET Core is designed as pluggable framework to include and use only necessary packages, instead of including too many initial stuff.

Lets create HTML file named “index.html” under wwwroot folder.
Right click on wwwroot folder, Add New Item and create index.html file. This HTML page will act as default page.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>ASP.NET Core with Angular 2 </title>
</head>
<body>
<h1>Example of ASP.NET Core using Angular 2 with Visual Studio 2015</h1>
</body>

</html>

For ASP.NET Core to serve static files, we need to add Static Files middle ware in Configure method of Startup.cs page. Ensure that packages are restored properly. 

project.json is redesigned to make it better, we have Static Files middle ware to serve static assets like HTML, JS files etc.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseDefaultFiles();
app.UseStaticFiles();
loggerFactory.AddConsole();

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}

Run the application now, ASP.NET Core renders static HTML page 












Step 3: What is TypeScript?

1. It is a typed super set of JavaScript that compiles to plain JavaScript. Any TypeScript code that runs in browser is plain JavaScript so its “Any browser. Any host. Any OS. 

2. The language consists of the new syntax, keywords, and type annotations. As a programmer, the language will be the component you will become most familiar with.

3. Understanding how to supply type information is an important foundation for the other components because the compiler and language service are most effective when they understand the complex structures you use within your program.

4. The Compiler performs the type erasure and code transformations that convert your TypeScript code into JavaScript.

5. It will emit warnings and errors if it detects problems and can perform additional tasks such as combining the output into a single file, generating source maps, and more.

6. The Language Service provides type information that can be used by development tools to supply intellisense, type hinting, re-factoring options, and other creative features based on the type information that has been gathered from the written program.

Step 4: Adding TypeScript in ASP.NET Core
Firstly created “Scripts” folder by right click project “CoreAngular2”. Here in this folder, we will add TypeScript Configuration file to use various settings of typescript.
Right Click on “Scripts” folder, Add new file by selecting from template TypeScript JSON Configuration File as shown below
















The reason to add this file in “Scripts” folder is that “Scripts folder will now act as VIRTUAL TYPESCRIPT project” and whenever we write any Typescript code in “Scripts” it will be automatically TRANSPILE’D to JavaScript.

Add TypeScript file called “app.ts” from Add New File options on “Scripts” folder.

Step 5: Output Directory for Compiled TypeScript files to wwwroot In beginning, I mentioned that “TypeScript compiles to plain JavaScript that runs in a browser”. 

The obvious question is where will compiled plain JavaScript will be placed?
As we are using ASP.NET Core, we have “wwwroot” which will serve assets directly to clients, including HTML files, CSS files, image files, and JavaScript files. The wwwroot folder is the root of your web site.

Now lets open “tsconfig.json“, we need to add configuration entry as “outDir” i.e. Output Directory so that compiled TypeScript files are copied there.

{
"compilerOptions": {
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"target": "es5",
"outDir": "../wwwroot/scripts"
},
"exclude": [
"node_modules",
"wwwroot"
]
}

Just compile once to see that app.ts is compiled to app.js under wwwroot folder along with its mapping.

























Step 6: Writing TypeScript code in app.ts


It’s time to write code in app.ts file. Below code is a mix of TypeScript Code and usual plain JavaScript code. This shows that “Any JavaScript code is valid TypeScript Code”

//Person is now string
function Welcome(person: string) {
return "Hello, " + person;
}

function ClickMeButton() {
var user = "Sandeep Jamkar";
document.getElementById("divMsg").innerHTML = Welcome(user);
}

Open index.html and copy this code. It has reference to app.js in HEAD section, it signifies that wwwroot acts as root folder of our ASP.NET Core. 

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>ASP.NET 5 TypeScript</title>
<!-- app.js is loaded from wwwroot folder -->
<script src="scripts/app.js"></script>
</head>
<body>
<h3>Example of ASP.NET Core using Angular 2 with Visual Studio 2015</h3>
<input type="button" style="width:70px;" value="Click Me" onclick="ClickMeButton()" />
<div id="divMsg"></div>
</body>
</html>

Run the application, Click the “Click Me” button to see a welcome message.



Step 7: What is so special here? Build errors in TypeScript code

TypeScript is special because it can do Type checking when doing a build. Function “Welcome” takes a string as a parameter. What if I make it as a number and check?


















Let’s see what is happening here.
1. Function “Welcome” takes parameter “Person” as number making it strongly typed.
2. Passing variable  “user” containing a string. It’s obvious that NUMBER isn’t STRING
3. Build errors clearly stating that its assignment error.
This is one of features TypeScript provides, making it special.



No comments:

Post a Comment