An Observable is a way to execute asynchronous
operations, in Angular Observable is supported using the RxJs library. An Observable
makes an asynchronous request and returns the success response or an error if
the request fails. The most common usage of observable is to make API calls to
services to get data. Let us see on how to make async calls using observable to
get data and display it in UI using Angular.
The Angular HttpClient library by default gives an Observable, let us use the Observable to get API data and display the results in the Component UI.
The Angular HttpClient library by default gives an Observable, let us use the Observable to get API data and display the results in the Component UI.
Let us extend our previous Promise example, we will use the same userdata.service from the previous example and add an Observable to it. This way we can compare the Promise and Observable in the same example code.
Modify the service code to add a new method getUsersObservable.
import { Injectable } from '@angular/core';
import
{ HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export
class UserdataService {
constructor(private http: HttpClient) { }
getUsersPromise() {
return
this.http.get('https://jsonplaceholder.typicode.com/users')
.toPromise()
.then(res => res)
.catch(err => {
return
Promise.reject(err.json().error ||
'Server error');
});
}
//
getUsersObservable() {
return this.http.get('https://jsonplaceholder.typicode.com/users')
}
}
Notice that the Observable code is very short when compared to the promise code, this is because Angular supports Observable by default. Next we will modify our component code to call this method and get the response from the Observable.
import { Component } from '@angular/core';
Notice that the Observable code is very short when compared to the promise code, this is because Angular supports Observable by default. Next we will modify our component code to call this method and get the response from the Observable.
import { Component } from '@angular/core';
import
{ UserdataService } from './userdata.service';
import
{ HelloService } from './hello.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export
class AppComponent {
userList;
userListObservable;
errorMessage: string;
constructor(private svcData: UserdataService,
private svcHello: HelloService) { }
title = 'Angular 6';
message = this.svcHello.getMessage();
ngOnInit() {
this.getDataPromise();
this.getDataObservable();
}
getDataPromise() {
this.svcData.getUsersPromise()
.then(response => {
this.userList = response;
},
error => {
console.error('An error occurred in
retrieving User list.', error);
});
}
getDataObservable() {
this.svcData.getUsersObservable().subscribe(
data => this.userListObservable = data,
err => this.errorMessage = err.status + ' - ' + err.statusText
);
}
}
Finally we will modify our component template to display the results from the Observable.
<div style="text-align:left">
Finally we will modify our component template to display the results from the Observable.
<div style="text-align:left">
<p class="title">Welcome
to {{ title }}!</p>
<p
class="msg">Message from Service: {{ message }}!</p>
<p class="title">{{
errorMessage }}</p>
<p>Data from
Promise</p>
<ul>
<li *ngFor="let user of
userList">
{{ user.name }} - {{ user.email }}
</li>
</ul><br/>
<p>Data from Observable</p>
<ul>
<li *ngFor="let user of
userListObservable">
{{ user.name }} - {{ user.email }}
</li>
</ul>
</div>That’s it we are done, run the sample and we can see the output as follows. Notice that the Promise and observable are displaying the same exact data, these are 2 different ways to make asynchronous calls to get API data.
No comments:
Post a Comment