Services in Angular Part 2 - Fetch data using HTTP and Observables
In my previous article on Angular Services, I talked about handling data using an array with the help of a service. Today I'm going to go far from it and use data included in a JSON file. I think now you have the basic understanding on services..If not, visit my Services in Angular article. Then come to read this one!
First, I will explain some basic things we needed in this tutorial..
What is HTTP Mechanism in Angular?
Angular service sends a HTTP Request to a Database or Web API to fetch data and after a successful evaluation, a HTTP response is received back as an Observable.
What is an Observable?
Simply it's a HTTP Response/Sequence of items that arrives asynchronously over time.
This is the process in a diagram.
When the HTTP Response is received as an Observable, we have to cast it into an array. Then it is provided to the relevant components which are subscribed to the particular service.
What is RxJS?
It's a library that helps to work with Angular applications. It's just an external library and reactive extension for JavaScript.
First, I will explain some basic things we needed in this tutorial..
What is HTTP Mechanism in Angular?
Angular service sends a HTTP Request to a Database or Web API to fetch data and after a successful evaluation, a HTTP response is received back as an Observable.
What is an Observable?
Simply it's a HTTP Response/Sequence of items that arrives asynchronously over time.
This is the process in a diagram.
When the HTTP Response is received as an Observable, we have to cast it into an array. Then it is provided to the relevant components which are subscribed to the particular service.
What is RxJS?
It's a library that helps to work with Angular applications. It's just an external library and reactive extension for JavaScript.
Ok guys! We are are ready now..Without more discussions, let's move on..
Here I use the previously created project to explain you the basics.. If you want you can create new one..
Open the project in a text editor like VS Code.
There are 4 main steps to use a service via HTTP mechanism.
1. Make a HTTP Request from the service
2. Receive the Observable and cast in into an array
3. Subscribe to the observable from components
4. Assign the array to a local variable
Step 1 - Make a HTTP Request from the service
For this we need to import HttpClientModule into AppModule. Then register the service in providers meta data.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { UserListComponent } from './user-list/user-list.component';
import { UserService } from './user.service';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent,
UserListComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [UserService],
bootstrap: [AppComponent]
})
export class AppModule { }
Create the service called user => ng g s user
To use HTTP in our service class, we declare it as a dependency in the constructor of service class. Create a local variable called http having the type of HttpClient to refer an instance of HttpClient. Now we are ready to make a HTTP request! We will use a method called getUsers for this.
Create the JSON file to include data
Why we are using a JSON?
Actually we need a web API or a DB server to get data from HTTP. Since we are not having it, we create a JSON and get its physical location as a URL to act as a web server.
In your project, there's a folder called assets. Create a folder in it and name it as data (These names are not fixed ones..Just names). Then in this data folder, create a file called users.json. Place a json object array to define data.. See the code below.
assets/data/users.json
assets/data/users.json
[
{
"id": 1,
"name": "salitha",
"job": "Web Developer"
},
{
"id": 2,
"name": "chathuranga",
"job": "UI Designer"
},
{
"id": 3,
"name": "techpool",
"job": "Blogger"
}
]
Now we can use this file to fetch data. How do we do it? We can use its URL. See here...
src/app/user.service.ts
import { HttpClient} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { User } from './user';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class UserService {
private _url = '/assets/data/users.json';
constructor(private http: HttpClient) { }
getUsers () {
return this.http.get(this._url);
}
}
Still not done! There are errors to be handled. Next step will fix some of them..
Step 2 - Cast the Observable into an array
We need to convert the Observable into a readable array in order to use in components. So I create a class called User. This can be a class or interface. This class defines the users json data. Create this class in src/app folder.
export class User {
id: number;
name: string;
job: string;
}
Then the data returns from getUsers method should be having the declared User return type. The modified getUsers method will be like this. Replace the code with this.
getUsers (): Observable<User[]> {
return this.http.get<User[]>(this._url);
}
Step 3 & 4 - Subscribe to the observable and Assigning
Now open the UserListComponent we have previously created. Or you can create it now using cmd!ng g c user-list
Open the TS tile and place this code in it. We are going to subscribe to the service in the ngOnInit life-cycle hook.
user-list/user-list.component.ts
user-list/user-list.component.ts
import { Component, OnInit } from '@angular/core';
import { UserService } from '../user.service';
@Component({
selector: 'app-user-list',
templateUrl: './user-list.component.html',
styleUrls: ['./user-list.component.css']
})
export class UserListComponent implements OnInit {
public users: any[] ;
constructor(private _userService: UserService) { }
ngOnInit() {
this._userService.getUsers().subscribe(data => this.users = data);
}
}
Now modify the user-list.component.html file to render the view in your web browser. Using a ngFor directive, we can loop the data getting from the array.
user-list/user-list.component.html
user-list/user-list.component.html
<div class="container">
<div class="row">
<div class="col-lg-3"></div>
<div class="col-lg-6">
<h3 class="text-center">List of Users</h3><br>
<table class="table table-bordered">
<thead>
<th>ID</th>
<th>Name</th>
<th>Job</th>
</thead>
<tbody>
<tr *ngFor="let item of users">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>{{ item.job }}</td>
</tr>
</tbody>
</table>
</div>
<div class="col-lg-3"></div>
</div>
<br>
</div>
Finally we have to give this UserListComponent to the AppComponent foe rendering in the browser. Open app.component.html and place this code.
<div style="text-align:center; margin-top: 30px;">
<app-user-list></app-user-list>
</div>
Now navigate into the project from your cmd and type ng serve -o to open the project in web browser. It should be like this..
Guy!! We have now finished the Angular Services 2nd tutorial. I wanted to give the real feeling to you how the HTTP works in Angular. Here I used a JSON file URL. You can replace it with a URL for a web API written in PHP. If I get a chance I will try to explain it.
Other than that, I will explain some more basic concepts in Angular in future. Till then,
Bye guys!
Guy!! We have now finished the Angular Services 2nd tutorial. I wanted to give the real feeling to you how the HTTP works in Angular. Here I used a JSON file URL. You can replace it with a URL for a web API written in PHP. If I get a chance I will try to explain it.
Other than that, I will explain some more basic concepts in Angular in future. Till then,
Bye guys!
6 Comments
Thanks for posting this article.Keep on sharing.
ReplyDeleteFull Stack online Training
Full Stack Training
Full Stack Developer Online Training
Full Stack Training in Hyderabad
Full Stack Training in Ameerpet
Full Stack Training Institute
Thanx Vishnu!
DeleteIf you are looking for the best Angular developmentcompany in USA, you may search for the same online.
ReplyDeleteVist cloudi5 blog https://www.cloudi5.com/blog/angularjs-framework-the-web-designers-prime-preference-89 to know more about angular js
ReplyDeleteThank you ever so for you article. Really Cool.
ReplyDeleteSAP Bods training
Very useful article! To support Angular Web Development I would also like to share, There is data on 845,382 companies using Angular and updates on daily a daily basis. Constantly, Angular Web Development Company are growing rapidly with the increasing demands of Angular Web development.
ReplyDelete