Angular 2 - CRUD Operations With Web API And Entity Framework

Before moving ahead, I would recommend you read my previous articles which explain how to install npm and add other mandatory files.

Getting Started

  • Start Visual Studio.
  • Create a new website.
  • Provide the name and the location of the website.
  • Click "Next".

After adding all mandatory Angular 2 files like systemjs.config.js, tsconfig.json and node_modules, here is my systemjs.config.js.

  1. /**  
  2.  * System configuration for Angular samples  
  3.  * Adjust as necessary for your application needs.  
  4.  */  
  5. (function(global) {  
  6.     System.config({  
  7.         paths: {  
  8.             // paths serve as alias  
  9.             'npm:''node_modules/'  
  10.         },  
  11.         // map tells the System loader where to look for things  
  12.         map: {  
  13.             // our app is within the app folder  
  14.             app: '/app',  
  15.             // angular bundles  
  16.             '@angular/core''npm:@angular/core/bundles/core.umd.js',  
  17.             '@angular/common''npm:@angular/common/bundles/common.umd.js',  
  18.             '@angular/compiler''npm:@angular/compiler/bundles/compiler.umd.js',  
  19.             '@angular/platform-browser''npm:@angular/platform-browser/bundles/platform-browser.umd.js',  
  20.             '@angular/platform-browser-dynamic''npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',  
  21.             '@angular/http''npm:@angular/http/bundles/http.umd.js',  
  22.             '@angular/router''npm:@angular/router/bundles/router.umd.js',  
  23.             '@angular/forms''npm:@angular/forms/bundles/forms.umd.js',  
  24.             // other libraries  
  25.             'rxjs''npm:rxjs',  
  26.             'angular-in-memory-web-api''npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',  
  27.             'ng2-bs3-modal''npm:/ng2-bs3-modal'  
  28.         },  
  29.         // packages tells the System loader how to load when no filename and/or no extension  
  30.         packages: {  
  31.             app: {  
  32.                 main: 'main.js',  
  33.                 defaultExtension: 'js'  
  34.             },  
  35.             rxjs: {  
  36.                 defaultExtension: 'js'  
  37.             },  
  38.             'ng2-bs3-modal': {  
  39.                 main: '/bundles/ng2-bs3-modal.js',  
  40.                 defaultExtension: 'js'  
  41.             }  
  42.         }  
  43.     });  
  44. })(this);  

In this file, you can change your app folder name or path and you can change node_modules path.

tsconfig.json

  1. {  
  2.     "compilerOptions": {  
  3.         "target""es5",  
  4.         "module""commonjs",  
  5.         "moduleResolution""node",  
  6.         "sourceMap"true,  
  7.         "emitDecoratorMetadata"true,  
  8.         "experimentalDecorators"true,  
  9.         "lib": ["es2015""dom"],  
  10.         "noImplicitAny"false,  
  11.         "suppressImplicitAnyIndexErrors"true  
  12.     }  
  13. }  
First of all, add a new item using right-click on solutions and go to data tab and select ADO.NET Entity Data Model. Here is my entity model diagram.

 

Now, add a new Web API Controller in controller folder like this.

 

Now, add Web API code.
  1. public class AlbumAPIController: BaseAPIController {  
  2.     // GET api/<controller>  
  3.     public HttpResponseMessage Get() {  
  4.         return ToJson(MusicStoreDB.Albums.AsEnumerable());  
  5.     }  
  6.     // POST api/<controller>  
  7.     public HttpResponseMessage Post([FromBody] Album value) {  
  8.         MusicStoreDB.Albums.Add(value);  
  9.         return ToJson(MusicStoreDB.SaveChanges());  
  10.     }  
  11.     // PUT api/<controller>/5  
  12.     public HttpResponseMessage Put(int id, [FromBody] Album value) {  
  13.         MusicStoreDB.Entry(value).State = EntityState.Modified;  
  14.         return ToJson(MusicStoreDB.SaveChanges());  
  15.     }  
  16.     // DELETE api/<controller>/5  
  17.     public HttpResponseMessage Delete(int id) {  
  18.         MusicStoreDB.Albums.Remove(MusicStoreDB.Albums.FirstOrDefault(x => x.AlbumId == id));  
  19.         return ToJson(MusicStoreDB.SaveChanges());  
  20.     }  
  21. }  

In my Web API, as you can see, I am inheriting by BaseAPIController. Here is the code for that.

  1. public class BaseAPIController: ApiController {  
  2.     protected readonly MVCMUSICSTOREEntities MusicStoreDB = new MVCMUSICSTOREEntities();  
  3.     protected HttpResponseMessage ToJson(dynamic obj) {  
  4.         var response = Request.CreateResponse(HttpStatusCode.OK);  
  5.         response.Content = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json");  
  6.         return response;  
  7.     }  
  8. }  

BaseAPI is a new API which converts result in JSON format.

If you are not working on an MVC project, then add a new class in App_Start folder.

  1. public static class WebApiConfig {  
  2.     public static void Register(HttpConfiguration config) {  
  3.         // Web API configuration and services  
  4.         // Web API routes  
  5.         config.MapHttpAttributeRoutes();  
  6.         config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/octet-stream"));  
  7.         config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new {  
  8.             id = RouteParameter.Optional  
  9.         });  
  10.     }  
  11. }  

And register in Global.asax.

  1.  AreaRegistration.RegisterAllAreas();  
  2. GlobalConfiguration.Configure(WebApiConfig.Register);  
  3. FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
  4. RouteConfig.RegisterRoutes(RouteTable.Routes);  
  5. BundleConfig.RegisterBundles(BundleTable.Bundles);  

Now, let’s move to the app folder where we have all Angular files like module, routing, main, components, HTML, style sheets etc.

First of all, add a new TypeScript file named main.ts or you can add it as a new JavaScript file but the extension should be .ts.

main.ts

  1. import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';  
  2. import { AppModule } from './app.module';  
  3. platformBrowserDynamic().bootstrapModule(AppModule);  
The main.ts file has Angular module URL. You can change it if you have your module in other files. Here is my app.module code.

app.module.ts

  1. import { NgModule } from '@angular/core';  
  2. import { APP_BASE_HREF } from '@angular/common';  
  3. import { BrowserModule } from '@angular/platform-browser';  
  4. import { ReactiveFormsModule } from '@angular/forms';  
  5. import { AppComponent } from './app.component';  
  6. import { Ng2Bs3ModalModule } from 'ng2-bs3-modal/ng2-bs3-modal';  
  7. import { HttpModule } from '@angular/http';  
  8. import { routing } from './app.routing';  
  9. import { UserComponent } from './components/user.component';  
  10. import { HomeComponent } from './components/home.component';  
  11. import { CountryComponent } from './components/country.component';  
  12. import { ArticleComponent } from './components/article.component';  
  13. import { AdminComponent } from './components/admin.component';  
  14. import { UserService} from './Service/user.service'  
  15. import { CountryService} from './Service/country.service'  
  16. import { ArticleService} from './Service/article.service'  
  17. import { AdminService} from './Service/admin.service'  
  18. @NgModule({  
  19.    imports: [BrowserModule, ReactiveFormsModule, HttpModule, routing, Ng2Bs3ModalModule],  
  20.    declarations: [AppComponent, UserComponent, HomeComponent, CountryComponent, ArticleComponent, AdminComponent],  
  21.    providers: [{ provide: APP_BASE_HREF, useValue: '/' }, UserService, CountryService, ArticleService, AdminService],  
  22.    bootstrap: [AppComponent]  
  23. })  
  24. export class AppModule { }  
The app.module has references of all services, components, routing files.

Here is my routing:

App.routing.ts

  1. import { ModuleWithProviders } from '@angular/core';  
  2. import { Routes, RouterModule } from '@angular/router';  
  3. import { UserComponent } from './components/user.component';  
  4. import { HomeComponent } from './components/home.component';  
  5. import { CountryComponent } from './components/country.component';  
  6. import { ArticleComponent } from './components/article.component';  
  7. import { AdminComponent } from './components/admin.component';  
  8. const appRoutes: Routes = [  
  9.    { path: '', redirectTo: 'home', pathMatch: 'full' },  
  10.    { path: 'home', component: HomeComponent },  
  11.    { path: 'user', component: UserComponent },  
  12.    { path: 'country', component: CountryComponent },  
  13.    { path: 'article', component: ArticleComponent },  
  14.    { path: 'admin', component: AdminComponent }  
  15. ];  
  16. export const routing: ModuleWithProviders =  
  17. RouterModule.forRoot(appRoutes);  
If routing you can change according to your requirement.

app.component.ts

There are two ways to define html and css in component, one way is you can make html in template tag and the other is you can make a new html page and css and define url in templateUrl.

  1. import {  
  2.     Component  
  3. } from "@angular/core"  
  4. @Component({  
  5.     selector: "user-app",  
  6.     template: `    
  7. <div>    
  8. <nav class='navbar navbar-inverse'>    
  9. <div class='container-fluid'>    
  10. <ul class='nav navbar-nav'>    
  11.    <li><a [routerLink]="['home']">Home</a></li>    
  12.    <li><a [routerLink]="['user']">Users Management</a></li>    
  13.    <li><a [routerLink]="['country']">Country</a></li>    
  14.    <li><a [routerLink]="['article']">Article</a></li>    
  15. </ul>    
  16. </div>    
  17. </nav>    
  18.    <div class='container'>    
  19. <router-outlet></router-outlet>    
  20.    </div>    
  21.    </div>    
  22. `  
  23. })  
  24. export class AppComponent {} 
Here you can see selector is your component name and template has display html, the other way you can do it is like this:
  1. import { Component } from "@angular/core"  
  2. @Component({  
  3.    selector: "user-app",  
  4.    templateUrl: './app/app.component.html',  
  5.    styleUrls: ['./app/styles.css']  
  6.    })  
  7. export class AppComponent {}  
Here you need to give the html page's url and style url.

app.component.html

  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <head>  
  5.     <title></title>  
  6.     <meta charset="utf-8" /> </head>  
  7.   
  8. <body>  
  9.     <div>  
  10.         <nav class='navbar navbar-inverse'>  
  11.             <div class='container-fluid'>  
  12.                 <ul class='nav navbar-nav'>  
  13.                     <li><a [routerLink]="['home']">Home</a></li>  
  14.                     <li><a [routerLink]="['user']">Users Management</a></li>  
  15.                     <li><a [routerLink]="['country']">Country</a></li>  
  16.                     <li><a [routerLink]="['article']">Article</a></li>  
  17.                     <li><a [routerLink]="['admin']">Admin</a></li>  
  18.                 </ul>  
  19.             </div>  
  20.         </nav>  
  21.         <div class='container'>  
  22.             <router-outlet></router-outlet>  
  23.         </div>  
  24.     </div>  
  25. </body>  
  26.   
  27. </html>  
styles.css
  1. .html {  
  2.     overflow - y: scroll;  
  3.     overflow - x: hidden;  
  4. }  
  5. main {  
  6.     position: relative;  
  7.     padding - top: 60 px;  
  8. }  
  9. h1 {  
  10.     color: red;  
  11. }  
  12. h3 {  
  13.     color: green;  
  14. }  
Before adding other services and components and other related files, let’s work on index page. If you are using MVC applications then you need to add required files on _Layout.cshtml, if you are not using mcv then just add those files on index page.

_Layout.cshtml

  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <head>  
  5.     <meta charset="utf-8" />  
  6.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  7.     <title>@ViewBag.Title - My ASP.NET Application</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr")  
  8.     <script src="/node_modules/core-js/client/shim.min.js"></script>  
  9.     <script src="/node_modules/zone.js/dist/zone.js"></script>  
  10.     <script src="/node_modules/systemjs/dist/system.src.js"></script>  
  11.     <script src="/systemjs.config.js"></script>  
  12.     <script>  
  13.         System.import('app').catch(function(err) {  
  14.             console.error(err);  
  15.         });  
  16.     </script>  
  17. </head>  
  18.   
  19. <body>  
  20.     <div class="container body-content"> @RenderBody()  
  21.         <hr />  
  22.         <footer>  
  23.             <p>© @DateTime.Now.Year - My ASP.NET Application</p>  
  24.         </footer>  
  25.     </div> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body>  
  26.   
  27. </html>  

Index.cshtml

  1. @{  
  2.    ViewBag.Title = "Index";  
  3. }  
  4. <body>  
  5.    <user-app>Loading…<user-app>  
  6. </body>  

Now let’s add other services, components and other related files. Let’s add a new folder name Model in app directory and add some typescript files and add related properties.

user.ts

  1. export interface IUser {  
  2.    AlbumId: number,  
  3.    GenreId: number,  
  4.    ArtistId: number,  
  5.    Title: string,  
  6.    Price: string,  
  7.    AlbumArtUrl: string,  
  8.    Artist: string  
  9. }  

country.ts

  1. export class Country {  
  2.    constructor(  
  3.       public id: number,  
  4.       public name: string) { }  
  5. }  

state.ts

  1. export class State {  
  2.    constructor(  
  3.       public id: number,  
  4.       public countryid: number,  
  5.       public name: string) { }  
  6. }  

article.ts

  1. export class Article{  
  2. constructor(  
  3.    public Id: Number,  
  4.    public Title: string,  
  5.    public Summary: string  
  6.    ){}  
  7. }  

admin.ts

  1. export class Admin{  
  2.    constructor(  
  3.    public Id: Number,  
  4.    public Name: string  
  5.    ){}  
  6. }  

Now let’s add a new Shared folder and add two Typescript files:

global.ts

  1. export class Global {  
  2.    public static BASE_USER_ENDPOINT = 'api/albumapi/';  
  3. }  

enum.ts

  1. export enum DBOperation {  
  2.    create = 1,  
  3.    update = 2,  
  4.    delete =3  
  5. }  

Now add a new folder Services and add service Typescript files:

user.service.ts

  1. import {  
  2.     Injectable  
  3. } from '@angular/core';  
  4. import {  
  5.     Http,  
  6.     Response,  
  7.     Headers,  
  8.     RequestOptions  
  9. } from '@angular/http';  
  10. import {  
  11.     Observable  
  12. } from 'rxjs/Observable';  
  13. import 'rxjs/add/operator/map';  
  14. import 'rxjs/add/operator/do';  
  15. import 'rxjs/add/operator/catch';  
  16. @Injectable()  
  17. export class UserService {  
  18.     constructor(private _http: Http) {}  
  19.     get(url: string): Observable < any > {  
  20.         return this._http.get(url).map((response: Response) => < any > response.json())  
  21.             // .do(data => console.log("All: " + JSON.stringify(data)))    
  22.             .catch(this.handleError);  
  23.     }  
  24.     post(url: string, model: any): Observable < any > {  
  25.         let body = JSON.stringify(model);  
  26.         let headers = new Headers({  
  27.             'Content-Type''application/json'  
  28.         });  
  29.         let options = new RequestOptions({  
  30.             headers: headers  
  31.         });  
  32.         return this._http.post(url, body, options).map((response: Response) => < any > response.json()).catch(this.handleError);  
  33.     }  
  34.     put(url: string, id: number, model: any): Observable < any > {  
  35.         let body = JSON.stringify(model);  
  36.         let headers = new Headers({  
  37.             'Content-Type''application/json'  
  38.         });  
  39.         let options = new RequestOptions({  
  40.             headers: headers  
  41.         });  
  42.         return this._http.put(url + id, body, options).map((response: Response) => < any > response.json()).catch(this.handleError);  
  43.     }  
  44.     delete(url: string, id: number): Observable < any > {  
  45.         let headers = new Headers({  
  46.             'Content-Type''application/json'  
  47.         });  
  48.         let options = new RequestOptions({  
  49.             headers: headers  
  50.         });  
  51.         return this._http.delete(url + id, options).map((response: Response) => < any > response.json()).catch(this.handleError);  
  52.     }  
  53.     private handleError(error: Response) {  
  54.         console.error(error);  
  55.         return Observable.throw(error.json().error || 'Server error');  
  56.     }  
  57. }  

country.service.ts

  1. import { Injectable } from '@angular/core';  
  2. import { Country } from '../model/country';  
  3. import { State } from '../model/state';  
  4. @Injectable()  
  5. export class CountryService {  
  6. getCountries() {  
  7. return [  
  8.    new Country(1, 'United States'),  
  9.    new Country(2, 'India'),  
  10.    new Country(3, 'Australia'),  
  11.    new Country(4, 'New Zealand'),  
  12.    new Country(5, 'South Africa'),  
  13.    new Country(6, 'United Kingdom')  
  14. ];  
  15. }  
  16. getStates() {  
  17. return [  
  18.    new State(1, 1, 'Alabama'),  
  19.    new State(2, 1, 'Alaska'),  
  20.    new State(3, 1, 'Arizona'),  
  21.    new State(5, 1, 'Arkansas'),  
  22.    new State(6, 1, 'California'),  
  23.    new State(7, 1, 'Colorado'),  
  24.    new State(8, 1, 'Connecticut'),  
  25.    new State(9, 1, 'Delaware'),  
  26.    new State(10, 1, 'Florida'),  
  27.    new State(11, 1, 'Georgia'),  
  28.    new State(12, 1, 'Hawaii'),  
  29.    new State(13, 1, 'Idaho'),  
  30.    new State(14, 1, 'Illinois'),  
  31.    new State(15, 1, 'Indiana'),  
  32.    new State(16, 2, 'New Delhi'),  
  33.    new State(17, 2, 'Maharashtra'),  
  34.    new State(18, 2, 'Goa'),  
  35.    new State(19, 2, 'Punjab'),  
  36.    new State(20, 2, 'Haryana'),  
  37.    new State(21, 2, 'Uttar Pradesh'),  
  38.    new State(22, 2, 'Rajasthan'),  
  39.    new State(23, 2, 'Andhra Pradesh'),  
  40.    new State(24, 2, 'Jharkhand'),  
  41.       new State(25, 2, 'Madhya Pradesh'),  
  42.    new State(26, 3, 'New South Wales'),  
  43.    new State(27, 3, 'Tasmania'),  
  44.    new State(28, 3, 'Qweensland'),  
  45.    new State(29, 3, 'Western Australia'),  
  46.    new State(30, 3, 'Victoria'),  
  47.    new State(31, 4, 'Auckland'),  
  48.    new State(32, 4, 'Wellington'),  
  49.    new State(33, 4, 'Christchurch'),  
  50.    new State(34, 4, 'Hamilton'),  
  51.    new State(35, 4, 'Napier'),  
  52.    new State(31, 5, 'Eastern Cape'),  
  53.    new State(32, 5, 'Limpopo'),  
  54.    new State(33, 5, 'Mpumalanga'),  
  55.    new State(34, 5, 'North West'),  
  56.    new State(35, 5, 'Northern Cape'),  
  57.    new State(31, 6, 'Herefordshire'),  
  58.    new State(32, 6, 'Durham'),  
  59.    new State(33, 6, 'Manchester'),  
  60.    new State(34, 6, 'South Yorkshire'),  
  61.    new State(35, 6, 'Birmingham')  
  62. ];  
  63. }  
  64. }  

article.service.ts

  1. import { Injectable } from '@angular/core';  
  2. import { Article } from '../model/article';  
  3. @Injectable()  
  4. export class ArticleService {  
  5.    ARTICLES: Article[] = [  
  6.    { Id: 1, Title: 'Angular 2 - Getting Started', Summary: 'In this article, you will learn how to start working with Angular 2.' },  
  7.    { Id: 2, Title: 'How to detect image Faces and make Blur using Cognitive Face API with .NET Core', Summary: 'In this article, you will learn how to detect total faces and image and make them Blur using Cognitive Face API with .NET Core.' },  
  8.    { Id: 3, Title: 'Getting Started With Microsoft Project 2016', Summary: 'In this article, you will learn how to getting started with Microsoft Project 2016 from scratch.' },  
  9.    { Id: 4, Title: 'Get Image Attributes using Cognitive Services face API in WPF', Summary: 'In this article you will learn how to get the image attributes like Age, Gender using Cognitive Services face API in WPF.' },  
  10.    { Id: 5, Title: 'Cognitive Services face API in WPF', Summary: 'In this article, I will explain how to use Cognitive Services face API in WPF.' }  
  11.    ];  
  12. }  

admin.service.ts

  1. import { Injectable } from '@angular/core';  
  2. import { Admin } from '../model/admin';  
  3. @Injectable()  
  4. export class AdminService {  
  5.    ADMIN: Admin[] = [  
  6.    { Id: 1, Name: 'Raj Kumar' },  
  7.    { Id: 2, Name: 'Preeti' }  
  8.    ];  
  9. }  
Now let’s add new folder components and add some components and html and stylesheets:

user.component.ts

  1. import {  
  2.     Component,  
  3.     OnInit,  
  4.     ViewChild  
  5. } from '@angular/core';  
  6. import {  
  7.     UserService  
  8. } from '../Service/user.service';  
  9. import {  
  10.     FormBuilder,  
  11.     FormGroup,  
  12.     Validators  
  13. } from '@angular/forms';  
  14. import {  
  15.     ModalComponent  
  16. } from 'ng2-bs3-modal/ng2-bs3-modal';  
  17. import {  
  18.     IUser  
  19. } from '../Model/user';  
  20. import {  
  21.     DBOperation  
  22. } from '../Shared/enum';  
  23. import {  
  24.     Observable  
  25. } from 'rxjs/Rx';  
  26. import {  
  27.     Global  
  28. } from '../Shared/global';  
  29. @Component({  
  30.     templateUrl: 'app/Components/user.component.html'  
  31. })  
  32. export class UserComponent implements OnInit {  
  33.     @ViewChild('modal') modal: ModalComponent;  
  34.     users: IUser[];  
  35.     user: IUser;  
  36.     msg: string;  
  37.     indLoading: boolean = false;  
  38.     userFrm: FormGroup;  
  39.     dbops: DBOperation;  
  40.     modalTitle: string;  
  41.     modalBtnTitle: string;  
  42.     constructor(private fb: FormBuilder, private _userService: UserService) {}  
  43.     ngOnInit(): void {  
  44.         this.userFrm = this.fb.group({  
  45.             AlbumId: [''],  
  46.             GenreId: [''],  
  47.             ArtistId: [''],  
  48.             Title: ['', Validators.required],  
  49.             Price: [''],  
  50.             AlbumArtUrl: ['', Validators.required],  
  51.             Artist: ['']  
  52.         });  
  53.         this.LoadUsers();  
  54.     }  
  55.     LoadUsers(): void {  
  56.         this.indLoading = true;  
  57.         this._userService.get(Global.BASE_USER_ENDPOINT).subscribe(users => {  
  58.             this.users = users;  
  59.             this.indLoading = false;  
  60.         }, error => this.msg = < any > error);  
  61.     }  
  62.     addUser() {  
  63.         this.dbops = DBOperation.create;  
  64.         this.SetControlsState(true);  
  65.         this.modalTitle = "Add New User";  
  66.         this.modalBtnTitle = "Add";  
  67.         this.userFrm.reset();  
  68.         this.modal.open();  
  69.     }  
  70.     editUser(AlbumId: number) {  
  71.         this.dbops = DBOperation.update;  
  72.         this.SetControlsState(true);  
  73.         this.modalTitle = "Edit User";  
  74.         this.modalBtnTitle = "Update";  
  75.         this.user = this.users.filter(x => x.AlbumId == AlbumId)[0];  
  76.         this.userFrm.setValue(this.user);  
  77.         this.modal.open();  
  78.     }  
  79.     deleteUser(AlbumId: number) {  
  80.         this.dbops = DBOperation.delete;  
  81.         this.SetControlsState(false);  
  82.         this.modalTitle = "Confirm to Delete?";  
  83.         this.modalBtnTitle = "Delete";  
  84.         this.user = this.users.filter(x => x.AlbumId == AlbumId)[0];  
  85.         this.userFrm.setValue(this.user);  
  86.         this.modal.open();  
  87.     }  
  88.     onSubmit(formData: any) {  
  89.         this.msg = "";  
  90.         switch (this.dbops) {  
  91.             case DBOperation.create:  
  92.                 this._userService.post(Global.BASE_USER_ENDPOINT, formData._value).subscribe(data => {  
  93.                     if (data == 1) //Success    
  94.                     {  
  95.                         this.msg = "Data successfully added.";  
  96.                         this.LoadUsers();  
  97.                     } else {  
  98.                         this.msg = "There is some issue in saving records, please contact to system administrator!"  
  99.                     }  
  100.                     this.modal.dismiss();  
  101.                 }, error => {  
  102.                     this.msg = error;  
  103.                 });  
  104.                 break;  
  105.             case DBOperation.update:  
  106.                 this._userService.put(Global.BASE_USER_ENDPOINT, formData._value.AlbumId, formData._value).subscribe(data => {  
  107.                     if (data == 1) //Success    
  108.                     {  
  109.                         this.msg = "Data successfully updated.";  
  110.                         this.LoadUsers();  
  111.                     } else {  
  112.                         this.msg = "There is some issue in saving records, please contact to system administrator!"  
  113.                     }  
  114.                     this.modal.dismiss();  
  115.                 }, error => {  
  116.                     this.msg = error;  
  117.                 });  
  118.                 break;  
  119.             case DBOperation.delete:  
  120.                 this._userService.delete(Global.BASE_USER_ENDPOINT, formData._value.AlbumId).subscribe(data => {  
  121.                     if (data == 1) //Success    
  122.                     {  
  123.                         this.msg = "Data successfully deleted.";  
  124.                         this.LoadUsers();  
  125.                     } else {  
  126.                         this.msg = "There is some issue in saving records, please contact to system administrator!"  
  127.                     }  
  128.                     this.modal.dismiss();  
  129.                 }, error => {  
  130.                     this.msg = error;  
  131.                 });  
  132.                 break;  
  133.         }  
  134.     }  
  135.     SetControlsState(isEnable: boolean) {  
  136.         isEnable ? this.userFrm.enable() : this.userFrm.disable();  
  137.     }  
user.component.html
  1. <div class='panel panel-primary'>  
  2.     <div class='panel-heading'> User Management </div>  
  3.     <div class='panel-body'>  
  4.         <div class='table-responsive'>  
  5.             <div style="padding-bottom:10px"><button class="btn btn-primary" (click)="addUser()">Add</button></div>  
  6.             <div class="alert alert-info" role="alert" *ngIf="indLoading"><img src="../../images/loading.gif" width="32" height="32" /> Loading...</div>  
  7.             <div *ngIf='users && users.length==0' class="alert alert-info" role="alert">No record found!</div>  
  8.             <table class='table table-striped' *ngIf='users && users.length'>  
  9.                 <thead>  
  10.                     <tr>  
  11.                         <th>Title</th>  
  12.                         <th>Price</th>  
  13.                         <th>URL</th>  
  14.                         <th></th>  
  15.                     </tr>  
  16.                 </thead>  
  17.                 <tbody>  
  18.                     <tr *ngFor="let user of users">  
  19.                         <td>{{user.Title}}</td>  
  20.                         <td>{{user.Price}}</td>  
  21.                         <td>{{user.AlbumArtUrl}}</td>  
  22.                         <td> <button title="Edit" class="btn btn-primary" (click)="editUser(user.AlbumId)">Edit</button> <button title="Delete" class="btn btn-danger" (click)="deleteUser(user.AlbumId)">Delete</button> </td>  
  23.                     </tr>  
  24.                 </tbody>  
  25.             </table>  
  26.             <div> </div>  
  27.         </div>  
  28.         <div *ngIf="msg" role="alert" class="alert alert-info alert-dismissible"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button> <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span> <span class="sr-only">Error:</span> {{msg}} </div>  
  29.     </div>  
  30. </div>  
  31. <modal #modal>  
  32.     <form novalidate (ngSubmit)="onSubmit(userFrm)" [formGroup]="userFrm">  
  33.         <modal-header [show-close]="true">  
  34.             <h4 class="modal-title">{{modalTitle}}</h4>  
  35.         </modal-header>  
  36.         <modal-body>  
  37.             <div class="form-group">  
  38.                 <div> <span>Title*</span> <input type="text" class="form-control" placeholder="Title" formControlName="Title"> </div>  
  39.                 <div> <span>Price</span> <input type="text" class="form-control" placeholder="Price" formControlName="Price"> </div>  
  40.                 <div> <span>AlbumArtUrl*</span> <input type="text" class="form-control" placeholder="URL" formControlName="AlbumArtUrl"> </div>  
  41.             </div>  
  42.         </modal-body>  
  43.         <modal-footer>  
  44.             <div> <a class="btn btn-default" (click)="modal.dismiss()">Cancel</a> <button type="submit" [disabled]="userFrm.invalid" class="btn btn-primary">{{modalBtnTitle}}</button> </div>  
  45.         </modal-footer>  
  46.     </form>  
  47. </modal>  
home.component.ts
  1. import { Component } from "@angular/core";  
  2. @Component({  
  3.    template: `<h1>This is home page!</h1>`  
  4.    })  
  5.    export class HomeComponent{  
  6. }  

country.component.ts

  1. import {  
  2.     Component  
  3. } from '@angular/core';  
  4. import {  
  5.     CountryService  
  6. } from '../Service/country.service';  
  7. import {  
  8.     Country  
  9. } from '../model/country';  
  10. import {  
  11.     State  
  12. } from '../model/state';  
  13. @Component({  
  14.     selector: 'country-component',  
  15.     templateUrl: 'app/components/countrycomponent.html',  
  16.     providers: [CountryService]  
  17. })  
  18. export class CountryComponent {  
  19.     selectedCountry: Country = new Country(0, 'India');  
  20.     countries: Country[];  
  21.     states: State[];  
  22.     constructor(private _countryService: CountryService) {  
  23.         this.countries = this._countryService.getCountries();  
  24.     }  
  25.     onSelect(countryid) {  
  26.         this.states = this._countryService.getStates().filter((item) => item.countryid == countryid);  
  27.     }  
  28. }  
countrycomponent.html
  1. <div class='panel panel-primary'>  
  2.     <div class='panel-heading'> Country Management </div>  
  3.     <div class='panel-body'>  
  4.         <div class='table-responsive'> <label>Country:</label> <select (change)="onSelect($event.target.value)">    
  5. <option value="0">--Select Country--</option>    
  6. <option *ngFor="let country of countries" value={{country.id}}>{{country.name}}</option>    
  7. </select> <br /><br />  
  8.             <div> <label>State:</label> <select>    
  9. <option *ngIf='selectedCountry.id == 0' value="0">--Select State--</option>    
  10. <option *ngFor="let state of states " value={{state.id}}>{{state.name}}</option>    
  11. </select> </div>  
  12.         </div>  
  13.     </div>  
  14. </div>  
article.component.ts
  1. import { Component } from '@angular/core';  
  2. import { ArticleService } from '../Service/article.service';  
  3. import { Article } from '../Model/Article';  
  4. @Component({  
  5.    selector: 'article-component',  
  6.    templateUrl: 'app/components/articlecomponent.html',  
  7.    providers: [ArticleService]  
  8. })  
  9. export class ArticleComponent {  
  10.    articles: Article[];  
  11.    constructor(private _articleService: ArticleService) {     
  12.    }  
  13. }  
articlecomponent.html
  1. <div class='panel panel-primary'>  
  2. <div class='panel-heading'>  
  3. Article Management  
  4. </div>  
  5. <div class='panel-body'>  
  6. <div class='table-responsive'>  
  7.    <h1>Article list</h1>  
  8. </div>  
  9. </div>  
  10. </div>  
admin.component.ts
  1. import { Component } from '@angular/core';  
  2. import { AdminService } from '../Service/admin.service';  
  3. import { Admin } from '../Model/admin';  
  4. @Component({  
  5.    selector: 'admin-component',  
  6.    templateUrl: 'app/components/admincomponent.html',  
  7.    providers: [AdminService]  
  8. })  
  9. export class AdminComponent {  
  10.    admins: Admin[];  
  11.    constructor(private _adminService: AdminService) {  
  12.    }  
  13. }  
admincomponent.html
  1. <div class='panel panel-primary'>  
  2.    <div class='panel-heading'>  
  3.       Admin Management  
  4.    </div>  
  5.    <div class='panel-body'>  
  6.    <div class='table-responsive'>  
  7.       <h1>Admin list</h1>  
  8.    </div>  
  9.    </div>  
  10. </div>  
I think we are good now. Time to run the application to see the result screen. 
If your home page loaded without error that means everything is good. As you can see on the header we have four navigation menus, if you click on User Management:


Data is loading from database and routing is also working well. Most people ask me this question about routing in Angular 2, so I would recommend this article for routing as well.

Now click on Edit button.


Change something and click on Update button. If you want to delete any row then click on Delete button then this model screen should open.


If you want to add new data, then simply click on Add button.


Now let’s check other navigation clicks to check weather and see if everything is working or not.


You can select any country, then all related states will bind in drop down. If you click on Article then empty window will load because I did not do any functionality for this.


Conclusion

In this article, we learned the basics for Angular 2 like loading data from Web API, Routing, and use of services and components. If you have questions or comments, please drop me a line in the comments section.


Similar Articles