Motive
In this blog, we will understand the concepts of Angular 2, Web API, and SQL Server.
Introduction - Angular 2
- Angular (commonly referred to as "Angular 2+" or "Angular v2 and above") is a TypeScript-based product of Google and created by a community of individuals and corporations.
- This is not an MVC framework.
- It is an open-source front-end web application platform.
WebAPI
- A server-side web API is a programmatic interface consisting of one or more publicly exposed endpoints to a defined request–response message system, typically expressed in JSON or XML, which is exposed via the web—most commonly by means of an HTTP-based web server
OverView
This is a step-by-step solution to set up Angular 2 with your Visual Studio 2017. In this project, I will create a simple web application for beginners. This application is used to bind the drop-down. We are just five steps away from Angular 2 application.
- Step 1 - Create a database (SQL Server).
- Step 2 - Create an API (web API)
- Step 3 - Create a connection with SQL and get data from SQL using Web API.
- Step 4 - Setup angular2 with Web API.
- Step 5 - Bind drop-down using Angular 2.
Needs
- Node JS (node version is 4.6.x or greater)
- NPM (Node Package Manager)( version 3.x.x or greater)
- Visual Studio 2017.
- TypeScript (2.2 or greater).
Now, set up Angular 2 files with Visual Studio.
Step 1
- Create table Country(CountryId int Identity (1,1),CountryName varchar(50))
-
- insert intoCityvalues(India);
- insert intoCityvalues('Canada');
- insert intoCityvalues(Australia);
Step 2 - CREATE WEB API
- Open Visual Studio 2017 and create a new project.
- Go to File=>New=> Project=>Select Web from Right Side =>Select ASP .Net Web Application (.NET FrameWork).
- Give a name to the project and select the directory where you want to create the project.
- Now, you will see a new window. Please select MVC project.
Step 3 - Create a connection with SQL and get data from SQL using Web API.
You can do it with only three steps.
- SqlConnetion
- Model
- Buisnesslogic
The following code is used to GET the data from database.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- using System.Data;
- using System.Data.SqlClient;
- namespace WebApplication1.api {
- [RoutePrefix("api/DropDownBind")]
- publicclassDropDownBindController: ApiController {
-
- [HttpGet]
- public IHttpActionResult GetCountry() {
- var objlist = GetCountryList();
- return Ok(objlist.ToList());
- }
-
- public List < CountryModel > GetCountryList() {
- SqlConnection con = new SqlConnection("Data Source=ServerName;Initial Catalog=DatabaseName;Persist Security Info=True;User ID=sa;Password=123");
- con.Open();
- string sql = null;
- SqlCommand cmd = new SqlCommand(sql, con);
- SqlDataAdapter sd = new SqlDataAdapter(cmd);
- List < CountryModel > listdetail = new List < CountryModel > ();
- try {
- cmd.CommandText = "Select * from Country";
- sd.SelectCommand = cmd;
- DataTable dt = new DataTable();
- sd.Fill(dt);
- for (int i = 0; i < dt.Rows.Count; i++) {
- CountryModel md1 = new CountryModel();
- md1.CountryName = dt.Rows[i]["CountryName"].ToString();
- md1.CountryId = Convert.ToInt16(dt.Rows[i]["CountryId"].ToString());
- listdetail.Add(md1);
- }
- } catch (Exception ex) {
- Console.WriteLine(ex);
- }
- return listdetail;
- }
-
- publicclassCountryModel {
- publicint CountryId {
- get;
- set;
- }
- publicstring CountryName {
- get;
- set;
- }
- }
- }
- }
NOTEPlease change your connection string.
Please check it in the following images.
Now build your project. While running your project, if you get an error in your output like "multiple actions were found", then please check:
appStart =>webApiConfig.cs=> Replace routetemplate: (api/{controller}/{id}), with routetemplate: (api/{controller}/{action}/{id}),
Step 4 - Set up Angular 2 with Web API project
- Go to the following link and download from this link.
- Download Angular project configuration from QuickStart.
- · src folder and it’s all contents
- · bs-config.json file
- · package.json file
- · tslint.json file
- Copy these above files and paste into your web application root directory. Now click on show all files in the solution explorer and right click on all those folder and files which you just pasted to your web app project and include these files in the solution.
- Restore package on right -- click on "package.json" file and select "Restore Packages" from the context menu.
- After restoration completion, you will see the message "Installing Packages Complete".
Note the following things carefully. Don’t include node_module in your solution.
Build the Angular 2 application using the folllowing steps,
- First => make your index.html file as your start up page. Right-click on src/index.html file in the solution explorer and select option “Set As Start Page”.
- To run your Angular project using Visual Studio via F5, you need to make the following changes,
- Change (in Index.html) the base path from <base href=”/”> to <base href=”/src/”> in the HTML file under src/app folder.
- Change the scripts also to use /node_modules with a slash instead of node_modules without the slash in the html file.
- Change(in systemjs.config.js file ),the NPM path from node_modules/ to /node_modules/ in the src/systemjs.config.js file.
- Run Aplication.
If you get this following error while running, please "set as startup page" to index.html.
And again run this,
Final OutPut
Step 5 - Bind dropdown using angular 2
First define an interface which will be the class definition to store the information from our ‘api’ file. Create a file called County.ts
Right click on app inside src (src=>app)
Add=>typescript file=>Country.ts
Insert the following code,
- exportinterface ICountry {
- CountryId: number;
- CountryName: string;
- }
Now add CountryService.ts file,
Now change
"app.component.ts".
Code of app.component.ts
- import { Component } from '@angular/core';
- import { ICountry } from './Country';
- import { CountryService } from './CountryService';
- import { Http, Response } from '@angular/http';
- import { Observable } from 'rxjs/Observable';
- import 'rxjs/add/operator/map';
- @Component({
- selector: 'my-app',
- template: `<h2>{{name}},<h2><br>
- Country:
- <select >
- <option value="0">Select</option>
- <option *ngFor="let obj of Country" value="{{obj.CountryId}}">
- {{obj.CountryName}}
- </option>
- </select>`,
- providers: [CountryService]
- })
- export class AppComponent {
- name = 'Hello Nav';
- Country: ICountry[];
- constructor(private componentName: CountryService) {
- }
- ngOnInit(): void {
- this.componentName.getCountry()
- .subscribe(response => (this.Country) = response);
- }
- }
Now change your app.module.ts file.
Code => app.module.ts
- import { NgModule } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
- import { HttpModule } from '@angular/http';
- import { AppComponent } from './app.component';
- import { CountryService } from './CountryService';
- @NgModule({
- imports: [BrowserModule, HttpModule ],
- declarations: [ AppComponent ],
- bootstrap: [ AppComponent ]
- })
- export class AppModule { }
Finally build your project,
Thanks for reading.