Show data using Web API and Service in Angular 2

Before moving ahead, you need to configure your Angular 2 application. Follow these articles first:

Getting Started

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

Here is my cricketer Web API.


Let’s add a model component, provide an appropriate name, and add reference of model class and other important assemblies.

  1. export class Cricketer {  
  2. constructor(  
  3. ID: number,  
  4. Name: string,  
  5. ODI: number,  
  6. Test: number  
  7. ) { }  
  8. }  

 

Now, let’s add a new service component and provide name.

  1. import { Injectable } from '@angular/core';  
  2. import { Http, Headers, RequestOptions, Response } from '@angular/http';  
  3. import { Cricketer } from './Cricketer';  
  4. import { Observable, Subject } from 'rxjs/Rx';  
  5. import 'rxjs/Rx'; //get everything from Rx  
  6. import 'rxjs/add/operator/toPromise';  
  7. @Injectable()  
  8. export class CricketerService {  
  9. apiUrl: string = "http://localhost:51453/api/Cricketers";// Web API URL  
  10. constructor(private _http: Http) { }  
  11. private RegenerateData = new Subject<number>();  
  12. RegenerateData$ = this.RegenerateData.asObservable();  
  13. AnnounceChange(mission: number) {  
  14. this.RegenerateData.next(mission);  
  15. }  
  16. // //  
  17. // getCricketers() {  
  18. // return this._http.get(this.apiUrl)  
  19. // .map((response) => response.json());  
  20. //}  
  21. getCricketers(): Observable<Cricketer[]> {  
  22. return this._http.get(this.apiUrl)  
  23. .map((res: Response) => res.json())  
  24. .catch((error: any) => Observable.throw(error.json().error || 'Server error'));  
  25. }  
  26. }  
Now, let’s add a cricketer component and give reference of service and model class.

 

  1. import { Component } from '@angular/core';  
  2. import { CricketerService } from './shared/cricketerservice';  
  3. import { Cricketer } from './shared/Cricketer';  
  4. import { Observable } from 'rxjs/Rx';  
  5. @Component({  
  6. moduleId: module.id,  
  7. selector: 'cricketer-component',  
  8. templateUrl: 'cricketercomponent.html',  
  9. providers: [CricketerService]  
  10. })  
  11. export class CricketerComponent {  
  12. cricketers: Observable<any[]>;  
  13. constructor(private _cricketerService: CricketerService) {  
  14. }  
  15. ngOnInit() {  
  16. this.getCricketers();  
  17. }  
  18. //  
  19. getCricketers() {  
  20. debugger  
  21. thisthis.cricketers = this._cricketerService.getCricketers();  
  22. }  
  23. }  
This is my cricketer component html.

 

  1. <div class="row">  
  2. <div class="table-responsive">  
  3. <table class="table ">  
  4. <thead class="thead-default">  
  5. <th>ID</th>  
  6. <th>Player</th>  
  7. <th>Total ODI</th>  
  8. <th>Total Test</th>  
  9. <th></th>  
  10. </thead>  
  11. <tbody>  
  12. <tr *ngFor="let cric of cricketers | async" scope="row">  
  13. <td>{{cric.ID}}</td>  
  14. <td>{{cric.Name}}</td>  
  15. <td>{{cric.ODI}}</td>  
  16. <td>{{cric.Test}}</td>  
  17. <td>  
  18. <button type="button" value="Update" class="btn btn-default" (click)='editCricketer(cric.ID, cric)'>Update</button>  
  19. <button type="button" value="Delete" class="btn btn-danger" (click)='deleteCricketer(cric.ID)'>Delete</button>  
  20. </td>  
  21. </tr>  
  22. </tbody>  
  23. </table>  
  24. </div>  
  25. <div class="col-md-offset-3 col-md-3">  
  26. <a routerLink="/addcricketercomponent" class="btn btn-warning">Add Player</a>  
  27. </div>  
  28. </div>  
Now, add the references of component and service in app.module.ts.

 

  1. import { NgModule } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { FormsModule } from '@angular/forms';  
  4. import { HttpModule } from '@angular/http';  
  5. import { CricketerComponent } from './cricketercomponent';  
  6. import { CricketerService } from './shared/cricketerservice';  
  7. import { app_routing } from './app.routing';  
  8. import { AddCricketerComponent } from './addcricketercomponent';  
  9. @NgModule({  
  10. imports: [BrowserModule, FormsModule, HttpModule, app_routing],  
  11. declarations: [CricketerComponent, AddCricketerComponent],  
  12. providers: [CricketerService],  
  13. bootstrap: [CricketerComponent, AddCricketerComponent]  
  14. })  
  15. export class AppModule { };  
Now, create a new index html page and add component name and other important files.

 

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <title></title>  
  5. <base href="/">  
  6. <meta charset="utf-8" />  
  7. <meta charset="utf-8" />  
  8. <meta name="viewport" content="width=device-width, initial-scale=1">  
  9. <link href="http://v4-alpha.getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet" />  
  10. <link href="app/css/styles.css" rel="stylesheet" />  
  11. <!-- Polyfill(s) for older browsers -->  
  12. <script src="node_modules/core-js/client/shim.min.js"></script>  
  13. <script src="node_modules/zone.js/dist/zone.js"></script>  
  14. <script src="node_modules/reflect-metadata/Reflect.js"></script>  
  15. <script src="node_modules/systemjs/dist/system.src.js"></script>  
  16. <!-- Configure SystemJS -->  
  17. <script src="systemjs.config.js"></script>  
  18. <script>  
  19. System.import('app').catch(  
  20. function (err)  
  21. { console.error(err); });  
  22. </script>  
  23. </head>  
  24. <body>  
  25. <header class="navbar navbar-inner navbar-fixed-top">  
  26. <nav class="container">  
  27. <div class="navbar-header">  
  28. <span class="app-title">CRUD Operations in Angular 2 using Web API</span>  
  29. </div>  
  30. </nav>  
  31. </header>  
  32. <section class="container">  
  33. <cricketer-component>Loading...</cricketer-component>  
  34. </section>  
  35. <footer class="footer">  
  36. <div class="container">  
  37. <p>@Copyright 2017.</p>  
  38. </div>  
  39. </footer>  
  40. </body>  
  41. </html>  
Now, it is time to run the application and see the output.

 



Conclusion

In this article, we have learnt how to get data from Web API and display using Observable in Angular 2. If you have any question or comment, drop me a line in C# Corner comments section.

Up Next
    Ebook Download
    View all
    Learn
    View all