Angular framework enables you to design front end of your application. Any dynamic application will always interact with backend server for data. In this article we will create a simple application that will interact with one of our backend service, get the data from webservice and display it on UI.
If you have not gone through my article “Angular: HelloWorld”. Please check it out first before proceeding further. We have already learned how to create a Hello World application. Now we will extend the same application it this article.
You will learn:
How to add Service Provider
How to enable your angular application to interact with backend
How to make a request to backend server
How to parse data coming from backend
How to display that data on your UI
Angular provides a very fine-grained architecture style of coding. With best practices, you should create a Service class, that will interact with your backend. It will help you to keep all backend related code at one place. You can call APIs defined in this Service class from any part of your application.
Let’s create a Service, let’s say DataService into our application (We will use Angular CLI for the same).
Open your command prompt and go to the home director of your project. Run
ng g service Data
“Data” is the name of the class you want to create but You will get the class name as “DataService”. Angular will always append Service to the name of your class. This will create two files data.service.spec.ts and data.service.ts. For now you may ignore data.service.spec.ts, because it’s for unit test for the service class.
Before using this class, you must declare this class into your providers list. For that you would have to modify your app.module.ts file. Open this file and find at the starting of this file add
import {DataService } from './data.service';
Now find providers array in the same file. Add DataService to that array like
providers: [DataService]
Your service class is ready to use now. But it does not contain any functionality.
Suppose, we want to retrieve items list from backend server. Let’s add this functionality.
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
class Item {
itemName: string;
itemPrice: number;
brandName: string;
}
@Injectable()
export class DataService {
constructor(private http: HttpClient) { }
getItems(itemsEndpoint: string): Item[] {
const items = [];
this.http.get(itemsEndpoint,
{headers: this.getHeaders()}).subscribe(res => {
const data: any = res;
for (let i = 0; i < data.items.length; i++) {
const item = new Item();
item.brandName = data.items[i].brandName;
item.itemName = data.items[i].itemName;
item.itemPrice = data.items[i].itemPrice;
items.push(item);
}
});
return items;
}
getHeaders(): HttpHeaders {
const headers = new HttpHeaders();
headers.append('Accept', 'application/json');
return headers;
}
}
Your class content should look like the above code. You may notice, in the above class we are using HttpClient class. Make sure you import it from '@angular/common /http'.
One more very important thing to pay attentions before using HttpClient in your class is importing HttpClientModule into app.modules.ts file. Otherwise you will be stuck into a problem. You final app.modules.tsshould look like this:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { DataService } from './data.service';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [DataService],
bootstrap: [AppComponent]
})
export class AppModule { }
We are all set for getting the data from backend now. We will display the data coming from web service endpoint say http://localhost:8080/api/v1/inventory/itemson our UI.
Lets modify our app.component.ts file.
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
items= [];
constructor(private dataService: DataService) {
}
ngOnInit() {
this.items = this.dataService.getItems('http://localhost:8080/api/v1/inventory/items');
}
}
Here we did three important modifications:
1. We have implemented onInit interface into our class. OnInit interface has a single method ngOnInit(). This method is a life-cycle hook on angular component. It will be called once when component is initialized. Remember OnInit imterface implementation is optional and type scripts uses it for type safety only. If you don’t implement this interface but add ngOnInit() method into your component class it will be the same.
2. A constructor has been created into this class. DataService class is injected into this component through this constructor.
3. in ngOnInit() method we have called getItems() method of dataservice with a webservice end point. Data returned by this API is assigned to a class level variable “items”.
As we want to display the items on UI. We would have to modify the html content. Open
app.component.html. Modify this file and it should look like
<div style="text-align:center">
<h1>Hurrah! I have created my first angular application.</h1>
<table border="1">
<thead>
<tr>
<th>#</th>
<th>Item Name</th>
<th>Brnad Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of items; let i = index;">
<td>{{i + 1}}</td>
<td>{{item?.itemName}}</td>
<td>{{item?.brandName}}</td>
<td>{{item?.itemPrice}}</td>
</tr>
</tbody>
</table>
</div>
You are all set and ready to run your Angular application. Make sure your backend server is working fine and returning expected json data.
Expected JSON from Backend:
{
"items": [
{ "itemName": "Item Name 1",
"brandName": "Brand Name 1",
"itemPrice": 26.5
}, {
"itemName": "Item Name 2",
"brandName": "Brand Name 2",
"itemPrice": 27.5
},
{
"itemName": "Item Name 3",
"brandName": "Brand Name 3",
"itemPrice": 28.5
},
{
"itemName": "Item Name 4",
"brandName": "Brand Name 4",
"itemPrice": 29.5
},
{
"itemName": "Item Name 5",
"brandName": "Brand Name 5",
"itemPrice": 30.5
}
]
}
Run ng serve -o command into your project’s home directory and it will run your application and open the browser. Which will look like
No comments:
Post a Comment