Hello all, I hope you all are doing well.
Why Observable came into in my mind??? Here is the reason,
I am implementing something interesting functionality in angular(article will be publish very soon), while implementing that functionality at that time I encountered with Observable and I want to cover this topic within that article but then later I thought I have to cover Observables topic in the different article, so here it is.
What are the Observables?
Observables in angular are used to ensure if particular properties are being returned from API call.
Observables help you manage asynchronous data, such as data coming from a backend service. Observables are used within Angular itself, including Angular’s event system and its HTTP client service. To use observables, Angular uses a third-party library called Reactive Extensions (RxJS).
if you want to understand in more details, please check out the below link.
https://angular.io/guide/observables
What are the benefits?
- Observables are used for data that have a different-2 property.
- Observables actually verify data and its type and performance wise it is much better than the calling the API's in the old fashion way.
- It is really recommended for the good performance of the application and to ensure that particular type of data is being returned.
Angular makes use of observables as an interface to handle a variety of common asynchronous operations. For example:
The EventEmitter class extends Observable.
The HTTP module uses observables to handle AJAX requests and responses.
The Router and Forms modules use observables to listen for and respond to user-input events.
How to use?
Step-1
Let's create an angular app,
go to your terminal.
ng new observable-app
Step-2
now create a full fake REST API with zero coding in less than 30 seconds.
here I used json-server.
https://github.com/typicode/json-server
npm install -g json-server
Step-3
create a db.json file in your root directory.
it looks like,
{
"languages": [
"Java",
"c#",
"Python"
],
"student": {
"id": 123,
"name": "john",
"phone": "123456",
"age": 21
},
"orderbook": {
"BuyOrders": [{
"OrderType": "LimitBid",
"Price": 497.02000000,
"Volume": 0.01000000
},
{
"OrderType": "LimitBid",
"Price": 490.00000000,
"Volume": 1.00000000
}
],
"CreatedTimestampUtc ": "2014-08-05T06:42:11.3032208Z",
"SellOrders": [{
"OrderType": "LimitOffer",
"Price": 500.00000000,
"Volume": 1.00000000
},
{
"OrderType": "LimitOffer",
"Price": 505.00000000,
"Volume": 1.00000000
}
]
},
"rates": [
{
"CurrencyCodeA": "Aud",
"CurrencyCodeB": "Usd",
"Rate": 0.86830000
}, {
"CurrencyCodeA": "Usd",
"CurrencyCodeB": "Aud",
"Rate": 1.15170000
}
],
"latestprices": {
"status": "ok",
"prices": {
"btc": {
"bid": "2352",
"ask": "3422",
"last": "5232"
},
"ltc": {
"bid": "0.342",
"ask":"0.343",
"last": "0.643"
},
"doge": {
"bid": "23.5",
"ask": "23.543",
"last": "234"
}
}
}
}
and then run this json-server to get the output.
json-server --watch db.json --port 4201
here I used --port 4201, you can run in any of your favorite port, except 4200(because already captured by angular).
Step-4
here we have a data, that contains the multiple types of values, such as integer, string.
to identify to api's data type, I am going to create a model in our /app directory. It is very beneficial for those who are already working on the same project or new member as well. Because they do not need to call the api and check the data type or check DB tables to identify the data type.
/app/models/
→ student.ts
→ orderbook.ts
under the student.ts,
export interface Student {
'id': number;
'name': string;
'phone': string;
'age': number;
}
under the orderbook.ts,
export interface OrderBook {
BuyOrders: Array<{
OrderType: string,
Price: number,
Volume: number
}>;
CreatedTimestampUtc: string;
SellOrders: Array<{
OrderType: string,
Price: number,
Volume: number
}>;
}
Step-5
so, our API is ready now. let's call these API's in our services.
create a new service to communicate with data.
ng g service apitest
apitest.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Student } from './models/student';
import { OrderBook } from './models/orderbook';
@Injectable()
export class ApitestService {
languages:string = 'http://localhost:4201/languages';
student:string = 'http://localhost:4201/student';
orderBook:string = 'http://localhost:4201/orderbook';
constructor(private httpClient: HttpClient) { }
getLanguages(): Observable<any> {
return this.httpClient.get(this.languages);
}
getStudent(): Observable<Student> {
return this.httpClient.get<Student>(this.student);
}
getOrderBook(): Observable<OrderBook> {
return this.httpClient.get<OrderBook>(this.orderBook);
}
}
Step-6
now import some important library and services
in app.module.ts,
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { ApitestService } from './apitest.service';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [ApitestService],
bootstrap: [AppComponent]
})
export class AppModule { }
here I imported, HttpClientModule, ApitestService and
in imports section, added HttpClientModule and
in providers, added ApitestService.
Step-7
go to the app.component.ts
import { Component, OnInit } from '@angular/core';
import { ApitestService } from './apitest.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private apitest: ApitestService) {}
ngOnInit() {
this.getLanguages();
this.getStudent();
this.getOrderBook();
}
getLanguages() {
this.apitest.getLanguages().subscribe(function(data) {
console.log('languages', data);
});
}
getStudent() {
this.apitest.getStudent().subscribe(function(data) {
console.log('Student', data);
});
}
getOrderBook() {
this.apitest.getOrderBook().subscribe(function (data) {
console.log("Order Book", data);
});
}
}
here we have methods to get the result and call these methods in ** ngOnInit()**.
Step-8
so we are ready to check the result. Start the ng server.
ng s
go to the http://localhost:4200/
here is the result,
I added some other complicated scenario. please check in a git repo.
Below is the git repo for your reference.
https://github.com/alokrawat050/observable-app
I hope it will be helpful to you.
Enjoy Coding...