In Focus

Consuming ASP.NET Web API In Angular - Part Four

In this, we will learn how to consume/use or fetch data with help of Asp.Net Web API in Angular. To achieve this task following are easy steps.

In this article, we will learn how to consume/use or fetch data with help of Asp.Net Web API in Angular. To achieve this task  we will follow some easy steps.

You can see our previous series of articles,

Step by Step Implementation

Create a new Angular project with CLI command.

Command

ng new ConsumeAspNetWebAPI

ng new ConsumeAspNetWebAPI

Following screenshot confirms the project was created successfully,

screenshot confirm project

Now start and switch to Visual Studio Code.

Click on File ---> Open Folder or Press ( CTRL + K CTRL + O)

Visual Studio Code

Visual Studio Code

After clicking on SELECT FOLDER button your project will open in Visual Studio code like this,

SELECT FOLDER button

As you know SRC folder is a source folder where we write our code to fetch data from Asp.Net Web API.

SRC folder

Click on SRC folder to view the default internal content SRC folder.

Create a folder named MODEL before we create our model class.

Right click on SRC folder and select NEW FOLDER,

NEW FOLDER

Switch to command window again to create a model (class) file called membermodel,

 command window

Command

ng g class model/membermodel <press enter>

Our Asp.Net Web API pass data ike,

  • MemberID
  • MemberName
  • PhoneNumber

    CODE

To implement this, we need to create a class as per the above format.

Now, this is the time to create a SERVICE folder where we keep our service.

Right click on SRC folder.

SRC folder

Switch to command window again to create a service file called Member

command window

You can see the above console screenshot SERVICE has been created successfully.

Now update/import link in the app.module.ts file of SERVICE

Insert the following line at the top of app.module.ts file.

  1. import { MemberService } from './services/member.service';  

Update the following line under @NgModule directive section of providers.

  1. providers: [MemberService],  

Now, to switch to component called app.component.ts file, update the following things:

Write import statement for MemberService:

  1. import {MemberService} from './services/member.service';  

Write dependency injection statement for MemberService.

  1. constructor(private memberserv : MemberService){  
  2. }  

Now, switch to MemberService.ts file to update code for testing.

Create a constructor inside MemberService.ts file.

  1. constructor() {   
  2.    console.log('Hello from service')  
  3.  }  

Now, it's time to check if our service working or not.

Execute the project by the following command,

command

command

 In the above screen you can see our project is executed on localhost with port number http://localhost::4200

OUTPUT

OUTPUT

The message in the above console shows our all settings for the service are perfect. Now we code further.

Now switch back to app.module.ts for import HTTP module at the top.

  1. import {HttpModule} from '@angular/http';  

Now add HTTPMODULE in imports

  1. imports: [  
  2.     BrowserModule,  
  3.     HttpModule  
  4.   ],  

Now switch to MemberService file to update the following codes:

  1. import {Http} from '@angular/http';  

Import Map setting just below the above code:

  1. import 'rxjs/add/operator/map';  

Now we add a method called GETALLMEMBERS

  1. GetAllMembers(){  
  2.   return this.http.get('http://localhost:52044/api/member').map(res =>res.json());  
  3. }  

Now switch back to app.component and add the following code inside the constructor:

  1. constructor(private memberserv : MemberService){  
  2. this.memberserv.GetAllMembers().subscribe((members) => {  
  3.   this.members = members;  
  4. });  
  5. }   

Now switch to app.component.html to print data on UI.

  1. <h1>Member Detail</h1>  
  2.   <ul>  
  3.     <li *ngFor = "let member of members">  
  4.         {{member.MemberName}} ----- {{member.PhoneNumber}}  
  5.     </li>  
  6.   </ul>  

OUTPUT

OUTPUT

While implementing Asp.Net Web API in Angular we interacted with the  following files,

SR. NO. FILE NAME FILE PATH DESCRIPTION
1 app.component.html src\app\app.component.html Default main component html file.
2 app.component.ts src\app\app.component.ts Default main component class file 
3 app.module.ts src\app\app.module.ts Heart of application all things should register with module.ts.
4 membermodel.ts src\app\model\membermodel.ts Model file which helps to generate view and port data to UI.
5 member.service.ts src\app\service\membe.service.ts Service class file which helps to fetch data from Web API. Fetches the data with HTTP module.

Full Source code of above main files,

Code of app.component.html

  1. <h1>Member Detail</h1>  
  2.   <ul>  
  3.     <li *ngFor = "let member of members">  
  4.         {{member.MemberName}} ----- {{member.PhoneNumber}}  
  5.     </li>  
  6.   </ul>  

Code of app.component.ts

  1. import { Component } from '@angular/core';  
  2. import { Membermodel } from './model/membermodel';  
  3. import {MemberService} from './services/member.service';  
  4.   
  5. @Component({  
  6.   selector: 'app-root',  
  7.   templateUrl: './app.component.html',  
  8.   styleUrls: ['./app.component.css']  
  9. })  
  10. export class AppComponent {  
  11.   title = 'app';  
  12.   members : Membermodel[];  
  13.   constructor(private memberserv : MemberService){  
  14.   this.memberserv.GetAllMembers().subscribe((members) => {  
  15.      this.members = members  
  16.     });  
  17.   }     
  18. }  

Code of app.module.ts

  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { AppComponent } from './app.component';  
  4. import { MemberService } from './services/member.service';  
  5. import {HttpModule} from '@angular/http';  
  6.   
  7. @NgModule({  
  8.   declarations: [  
  9.     AppComponent  
  10.   ],  
  11.   imports: [  
  12.     BrowserModule,  
  13.     HttpModule  
  14.   ],  
  15.   providers: [MemberService],  
  16.   bootstrap: [AppComponent]  
  17. })  
  18. export class AppModule { }  

Code of membermodel.ts

  1. export class Membermodel {  
  2.     memberid : number;  
  3.     membername : string;  
  4.     phonenumber : string;  

Code of member.service.ts

  1. import { Injectable } from '@angular/core';  
  2. import {Http} from '@angular/http';  
  3. import 'rxjs/add/operator/map';  
  4.   
  5. @Injectable()  
  6. export class MemberService {  
  7.   constructor(public http : Http) {   
  8.   }  
  9. GetAllMembers(){  
  10.   return this.http.get('http://localhost:52044/api/member').map(res =>res.json());  
  11. }  
  12. }  

Happy Coding…