Click here to Skip to main content
15,868,016 members
Articles / Web Development

ASP.NET Core 1.0 RC2 and Angular2 using WEB API

Rate me:
Please Sign up or sign in to vote.
4.90/5 (12 votes)
14 Jul 2016CPOL9 min read 43.5K   802   21   9
In this article, we will learn in detail about using Angular2 with ASP.NET Core 1.0 RC2 using WEB API.

Introduction

Image 1

In this article we will see in detail of using Angular2 with ASP.NET Core 1.0 RC2 using WEB API.

In our previous article  http://www.codeproject.com/Articles/1084085/ASP-NET-Core-MVC-Using-WEB-API-And-AngularJS  we have seen few basics of ASP.NET Core 1.0 and AnfularJS now we will see in detail about using WEB API and Angular2 in ASP.NET Core RC2.

In this article we will see in detail of how to

  • Create our ASP.NET Core 1.0 RC2 Web Application.
  • Creating MVC Model to add Student details.
  • Creating MVC Controller to return WEB API Method
  • How to add TypeScript JSON Configuration File
  • How to add grunt package using NPM configuration file
  • How to configure Grunt File.
  • Adding Dependencies to install Angular2 and all other files
  • How to create our Angular2 App, boot using Type Script file.
  • Creating HTML File
  • How to Run the Grunt file using Visual Studio Task Runner Explorer
  • Now It’s time to Run and view our Sample.
  • How to show the Angular2 Component result in our HTML page.

Reference website : https://angular.io/docs/ts/latest/tutorial/ ,

https://angular.io/docs/ts/latest/guide/server-communication.html

Prerequisites

Visual Studio 2015: You can download it from here.

ASP.NET Core 1.0 RC2: download link https://www.microsoft.com/net

https://www.microsoft.com/net/core#windows

Using the code

After installed both Visual Studio 2015 and ASP.NET Core 1.0 RC2. Click Start, then Programs and select Visual Studio 2015 - Click Visual Studio 2015. Click New, then Project, select Web and select ASP.NET Core Web Application. Enter your Project Name and click OK.

Image 2

Next select Web Application. If you are not hosting in Cloud then you can uncheck the Host in the Cloud at the bottom right corner. Click OK

Image 3

Now we have created our ASp.NET Core 1.0 Web application.

Image 4

Step 2: Creating MVC Model to return student list

We can create a model by adding a new class file in our Model Folder.

Image 5

Right click the Models folder and click new Item .Select Class and enter your class name as “StudentMasters.cs”

Image 6

Now add in this class we first create property variable,add student details to list and return the list .We will be using this list in our controller.

C#
public class StudentMasters
    {
        public int StdID { get; set; }
        public string StdName { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public string Address { get; set; }

        public StudentMasters(int ID, string Name, string email, string phone, string Addr)
        {
            StdID = ID;
       StdName = Name;
       Email = email;
        Phone = phone;
            Address = Addr;
    }

        public static List<StudentMasters> studetndDetails()
        {
            List<StudentMasters> listStudents = new List<StudentMasters>();
            listStudents.Add(new StudentMasters(1, "Shanu",  "shanu@shanumail.com",  "000000",  "korea"));
            listStudents.Add(new StudentMasters(2, "Afraz", "Afraz@gmail.com", "0000123", "korea"));
            listStudents.Add(new StudentMasters(3, "Afreen", "Afreen@gmail.com", "000643", "Seoul,Korea"));
            listStudents.Add(new StudentMasters(4, "Asha", "Asha@gmail.com", "00003455", "Madurai,India"));
            listStudents.Add(new StudentMasters(5, "Kather", "Kather@gmail.com", "000067567656", "Madurai,India"));

            return listStudents;
        }
    }

Step 3: Creating MVC Controller to return WEB API Method

We can create a controller by adding a new Empty API Controller in our Controller Folder.

Image 7

Right click the Controller folder and Add Controller .Select Empty API Controller and give the name as “StudentMastersController”

Image 8

In the controller we return the List result as IEnumerable in our Angular2 Component we will be using this web API method to return the data and bind in our HTML page.

C#
[Produces("application/json")]
    [Route("api/StudentMasters")]
    public class StudentMastersController : Controller
    {

        [HttpGet]
        public IEnumerable<StudentMasters> Get()
        {
            return StudentMasters.studetndDetails().ToList();
        }
    }

To test it we can run our project and copy the get method api path here we can see our API path for get is api/StudentMasters/

Run the program and paste the above API path to test our output.

Image 9

Step 4: How to add TypeScript JSON Configuration File

The TypeScript JSON file will file specifies the root files and the compiler options required to compile the project .To know more about TypeScript JSON Configuration kindly visit this sites

http://www.typescriptlang.org/docs/handbook/tsconfig-json.html ,

To create the TypeScript JSON file right click on you Project and Click Add new Item.

Image 10

Select TypeScript JSCON Configuration File and Click ok. The File will be look like below image.

Image 11

Now copy the below code and replace with your config file.

JavaScript
"compilerOptions": {
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "target": "es5",
 "sourceMap": true

Image 12

Step 5: How to add grunt package using NPM configuration file

Now we need to add a NPM Configuration File for adding a grunt package to run our java scripts.

As we have created as a Web Application the NPM Configuration File will be located in our project.

By default we can’t view our NPM Configuration File. The NPM Configuration File will be in the name of “package.JSON” . TO view that from the Solution Explorer click on “Show All Files”

Now open the “package.JSON” file .Now first we need to change the name to our project Solution name and add our grunt package .we can see the code here below the image.

Image 13

Here we have changed the name as our Solution name and also added the grunt package.

JavaScript
{
  "name": "test",
  "version": "0.0.0",
  "private": true,
"devDependencies": {
    "grunt": "1.0.1",
    "grunt-contrib-copy": "1.0.0",
    "grunt-contrib-uglify": "1.0.1",
    "grunt-contrib-watch": "1.0.0",
    "grunt-ts": "5.5.1",
    "gulp": "3.8.11",
    "gulp-concat": "2.5.2",
    "gulp-cssmin": "0.1.7",
    "gulp-uglify": "1.2.0",
    "rimraf": "2.2.8"
  }
}

Now save the package.json file and you should be able to see a grunt package under Dependencies/ npm Folder will be first Resorted and then installed.

Restoring :

Image 14

Al Installed:

Image 15

Step 6: Configure Grunt File.

Grunt is used to build all our client side resources like JavaScript for our project.

First step is to add a Grunt file to our project. Right click our project and Select Grunt Configuration File and click Add.

Image 16

After creating the file now s we need to edit this file to add load plugins, configure plugins and define tasks.

Here in our Grunt file we have first load plugins which we have added in our npm. Using loadNpmTask here we load 'grunt-contrib-copy ,'grunt-contrib-uglify' , 'grunt-contrib-watch'

Image 17

Next we configure the grunt add the app.js file in our wwwroot folder. All our Script files from Scripts folder result will be added in this app.js file. Next we need to copy all the Script file from 'node_modules/ to our local js Folder.

The watch plugin will be used to check for any changes on JavaScript file and update it app.js with all new changes.

JavaScript
/*
This file in the main entry point for defining grunt tasks and using grunt plugins.
Click here to learn more. http://go.microsoft.com/fwlink/?LinkID=513275&clcid=0x409
*/
module.exports = function (grunt) {
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-ts');
    grunt.initConfig({
        ts:
        {
            base:
            {
                src: ['Scripts/app/boot.ts', 'Scripts/app/**/*.ts'],
                outDir: 'wwwroot/app',
                tsconfig: './tsconfig.json'
            }
        },
        uglify:
        {
            my_target:
            {
                files: [{
                    expand: true,
                    cwd: 'wwwroot/app',
                    src: ['**/*.js'],
                    dest: 'wwwroot/app'
                }]
            },
            options:
            {
                sourceMap: true
            }
        },
        // Copy all JS files from external libraries and required NPM packages to wwwroot/js  
        copy: {
            main: {
                files:
                     [{
                         expand: true,
                         flatten: true,
                         src: ['Scripts/js/**/*.js', 'node_modules/es6-shim/es6-shim.min.js', 'node_modules/systemjs/dist/system-polyfills.js', 'node_modules/angular2/bundles/angular2-polyfills.js', 'node_modules/systemjs/dist/system.src.js', 'node_modules/rxjs/bundles/Rx.js', 'node_modules/angular2/bundles/angular2.dev.js'],
                         dest: 'wwwroot/js/',
                         filter: 'isFile'
                     }]
            }
        },
        // Watch specified files and define what to do upon file changes  
        watch: {
            scripts: {
                files: ['Scripts/**/*.js'],
                tasks: ['ts', 'uglify', 'copy']
            }
        }
    });
    // Define the default task so it will launch all other tasks  
    grunt.registerTask('default', ['ts', 'uglify', 'copy', 'watch']);
};

Step 7: Adding Dependencies to install Angular2 and all other files

We are using NPM to install our Angular2 in our web application. Open our Package.JSON file and the below dependencies.

JavaScript
"dependencies": {
    "@angular/http": "2.0.0-rc.1",
    "angular2": "^2.0.0-beta.8",
    "angular2-jwt": "0.1.16",
    "angular2-meteor": "0.5.5",
    "cors": "2.7.1",
    "systemjs": "0.19.22",
    "es6-promise": "^3.0.2",
    "es6-shim": "^0.33.3",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.2",
    "tsd": "^0.6.5",
    "zone.js": "0.5.15"
  },

The edited Package.json file will be look like below image.

Image 18

Save the file and wait for few second to complete all decencies installed.

Image 19

Step 8 How to create our Angular2 App, boot using Type Script file.

Now it’s time to create our Angular2 application. First create a Folder named Scripts. Right click our project and click add new Folder and name the folder name as “Scripts”. Now we will create our TypeScript files inside this Scripts folder.

To work with Angular2 we need to create 2 important TypeScript file.

  1. Component File where we write our Angular coding.
  2. Boot file: To run our component app .

Creating App TypeScript file:

Right Click on Scripts folder and click on add new Item. Select TypeScript File and name the file as App.ts and click Add.

Image 20

In App.ts file we has three parts first is the

  1. import part
  2. Next is component part
  3. Next we have is the class for writing our business logics.

Here we can see a simple basic one way binding example to display the welcome message in side h1 tag.Here.

  1. import part : first we import angular2 files to be used in our component here we import http for using http client in our Angular2 component and importing NgFor for using the looping and bind all the student details array value one by one,and also we are importing one more typescript export class name StudentMasters from the model file.
JavaScript
import { Component, Injectable} from 'angular2/core';
import { NgFor } from 'angular2/common';
import {Http, Headers, Response} from 'angular2/http';
import { StudentMasters } from './model';
import 'rxjs/Rx';

      2. Next is component part :

In component we have selector, directives and template. Selector is to give name for this app and in our html file we use this selector name to display in our html page. In template we write our code. IN template we bind the StudentMaster details using ngFOR.The student details will be loaded in our export class where we write all our business logic and http function to load data from WEB API.

HTML
@Component({
    selector: "my-app",
    directives: [NgFor],
    template: `
            <h1 style="color:#467813;">ASP.NET Core / Angular2 and WEB API Demo </h1>
<hr>
  <h2>A Simple demo made by : <span style="color:#8340AF;">{{myName}} </span> </h2>
  
<h2 style="color:#FF5733;"> Student Details retured from WEB API as JSON result  </h2>
 <h3 style="color:#C70039;">
   <ul>
      <li *ngFor="let std of student">
   <code> <span *ngFor="let stdArray of generateArray(std)"> {{stdArray}} </span> </code>
</li>
      
    </ul>
</h3>
              `,})

3. Export Class :

This is the main class where we do all our business logic and variable declaration to be used for in our component template.in this class we have created a method named getData() and in this method we get the API method result and bind the result to the student array. In our component template we will be binding the result from this student array.

JavaScript
export class AppComponent {
    student: Array<StudentMasters> = [];
    myName: string;
    constructor(public http: Http) {
        this.myName = "Shanu";
        this.getData();
    }

    getData() {

        this.http.get('api/StudentMasters')
            .map((res: Response) => res.json())
            .subscribe(
            data => { this.student = data },
            err => console.error(err),
            () => console.log('done')

            );
    }
    // to generate the JSON object as array
    generateArray(obj) {
        return Object.keys(obj).map((key) => { return obj[key] });
    }
}

Next we need to add the boot.ts file to run our app.

Creating boot TypeScript file:

Right Click on Scripts folder and click on add new Item. Select TypeScript File and name the file as boot.ts and click Add.

Image 21

In boot.ts file we add the below code. Here first we import bootsrap file to load and run our app file and also we import our app component. Note to import our app we need to give the same class name which was given in our app typescript file and give our app path in from  as ’./app’ .Next we run our app by adding the app name in bootstrap as bootstrap(myAppComponent);.

JavaScript
///<reference path="../node_modules/angular2/typings/browser.d.ts" />  

import {bootstrap} from 'angular2/platform/browser'
import {ROUTER_PROVIDERS} from "angular2/router";
import {HTTP_PROVIDERS, HTTP_BINDINGS} from "angular2/http";
import {AppComponent} from './app'

bootstrap(AppComponent, [HTTP_BINDINGS, HTTP_PROVIDERS]);

Creating model TypeScript file:

Right Click on Scripts folder and click on add new Item. Select TypeScript File and name the file as model.ts and click Add.

Image 22

We use this model typescript file to create our Studentmasters model and declare all the public properties which we created in our MVC model.

JavaScript
export class StudentMasters {
    constructor(
        public StdID: number,
        public StdName: string,
        public Email: string,
        public Phone: string,
        public Address: string
    ) { }
}

Step 9: Creating HTML File

Next we need to create our html page to view result.To add the HTML file right click on wwwroot folder and click add new item , give the name as index.html and click Add.

Image 23

In HTMl file replace the below code. Here we can see first in header part we add all the script reference file and in script we load our boot file to run our app.In body part we display the result using the component selector name .In our app component we have given the selector name as “myapp1”.In this HTML to display the result we add tag like this   <my-app>Please wait...</my-app>

HTML
<html>

<head>
    <title>ASP.NET Core: AngularJS 2 Demo</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 1. Load libraries -->
    <!-- IE required polyfills -->
    <script src="/js/es6-shim.min.js"></script>
    <script src="/js/system-polyfills.js"></script>
    <!-- Angular2 libraries -->
    <script src="/js/angular2-polyfills.js"></script>
    <script src="/js/system.src.js"></script>
    <script src="/js/Rx.js"></script>
    <script src="/js/angular2.dev.js"></script>
    <script src="/js/router.dev.js"></script>
    <script src="/js/http.dev.js"></script>
    <!-- Bootstrap via SystemJS -->
    <script>

        System.config
        ({
            packages:
            {
                "app":
                {
                    defaultExtension: 'js'
                },
                'lib': { defaultExtension: 'js' }
            }
        });
        System.import('app/boot').then(null, console.error.bind(console));
    </script>
</head>

<body>
    <!-- Application PlaceHolder -->
    <my-app>Please wait...</my-app>

</body>

</html>

So what is next we have successfully created our first Angular2 and Asp.Net core 1.0 web application and wait we have to do one more pending work to run our application? Yes we need to run our Grunt file to create our entire script file in our wwwroot scripts folder.

Step 8: Run the Grunt file using Visual Studio Task Runner Explorer

Now we need to run the Grunt file using Visual Studio Task Runner.

To view the Task Runner Click the menu View-> Other Windows,-> and click on Task Runner

Image 24

We can also open Task Runner by right click on our Gruntfile.js in Solution Explorer and click on Task Runner Explorer.

Image 25

Now we can see our Task Runner Explorer.

Image 26

Click on GruntFile.js and click on refresh button at top left.

Image 27

Now we can see all the GruntFile has been added.

Image 28

Right click the default under Alias Task and click Run.

Image 29

Now our Grunt file has been successfully run in our project. When we add a script file we can see new app.js file will be created in our wwwroot folder.

Image 30

Run the Program:

Here we can see all the data from WEB API has been bind to our HTML page using Angular2.

Image 31

History

ShanuASPNETCoreAngular2WEBAPI.zip - > 2016-07-11

License

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


Written By
Team Leader
India India
Microsoft MVP | Code Project MVP | CSharp Corner MVP | Author | Blogger and always happy to Share what he knows to others. MyBlog

My Interview on Microsoft TechNet Wiki Ninja Link

Comments and Discussions

 
QuestionGrant Error Pin
s4sajal28-Sep-16 4:40
s4sajal28-Sep-16 4:40 
AnswerRe: Grant Error Pin
Blagojce-MKD6-Nov-16 4:45
Blagojce-MKD6-Nov-16 4:45 
QuestionNice Article Pin
Rajendra Aloha25-Aug-16 0:44
Rajendra Aloha25-Aug-16 0:44 
GeneralNice Article Pin
Member 1259778115-Jul-16 4:17
Member 1259778115-Jul-16 4:17 
QuestionNice Pin
Vignesh Mani13-Jul-16 10:43
professionalVignesh Mani13-Jul-16 10:43 
QuestionAngular2 RC is way different. Pin
Member 1263361513-Jul-16 7:49
Member 1263361513-Jul-16 7:49 
QuestionDeploying Pin
jp2code12-Jul-16 6:35
professionaljp2code12-Jul-16 6:35 
QuestionWhy RC2? Pin
Andreas Kroll11-Jul-16 23:56
Andreas Kroll11-Jul-16 23:56 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey11-Jul-16 23:44
professionalManoj Kumar Choubey11-Jul-16 23:44 
Nice article, Thank you for the article, From Last Month I also started to using RC 2 template for angular and web API.

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.