Angular Observables
In Previous topic we have seen Angular Router and configure it. In this section we will take a look into Angular Observables.
Angular Observable ➤➤
Angular Observable is a function that converts ordinary stream of data in Observable stream of data.
In Order to use Observable we have to import "Observable" from "rxjs" into component that use it.
import { Observable } from 'rxjs';
Observable emits the value from the stream asynchronously. It emits the complete signal when the stream completes or an error signal for any errors.
The Observable starts to emit values only when someone subscribes to it.
Important Points :
- Observables are sequence of data that gets emitted asynchronously from time to time or over period time it means that observable will keep producing values.
- Observable provide support for passing messages between different parts of our application.
- Angular make use of Observables as an interface to handle a variety of common async operations.
- Observables are frequently used in Angular and are the recommended technique for event handling, async programming and handling multiple values
Observers ➤➤
- There is no use of observable unless someone consumes the value emitted by the Observable.
- When we create observable, we keep track on the observable using observer.
- Observer is continuously listening to observable.
- We can control when to start and end listening to Observable using Observer.
- Observer has 3 methods that we can use i.e. next(), error() and complete().
Observable Example ➤➤
import { Component, OnInit } from '@angular/core';
import { Observable, of } from 'rxjs';
@Component({
selector: 'app-teacher-dashboard',
templateUrl: './teacher-dashboard.component.html',
styleUrls: ['./teacher-dashboard.component.css']
})
export class TeacherDashboardComponent implements OnInit {
ObservableVarable$ : any; //Declared an Observable, best practice to use $ Sign with observable variable
ObservableUserArray : any;
constructor() { }
ngOnInit(): void {
this.ObservableUserArray = ['Akash','Ankit','Prabha','Anjali']; // Simple array with some
//value
//We will use this array to create an observable
//Two ways to create observable
// 1st : Using RxJS "of" operator
// 2nd : Using new Observable
//1st approach to get an observable
this.ObservableVarable$ = of(this.ObservableUserArray);
console.log("1st approach Observable" +this.ObservableVarable$);
//2nd Approach
new Observable(observer => {
setTimeout(() => {
observer.next("starting")
},2000);
setTimeout(() => {
observer.next("started")
},4000);
setTimeout(() => {
observer.next("completed")
},6000);
})
// Till here we have created a new observable but it will not impact anything
// as we dind't subscribed it yet.
// There are 3 ways we can subscribe to any observable
// -> Subscribe
// -> toPromise
// -> pipe
.subscribe({
next: data => {
console.log("Subscribed Data" +data)
},
error: err => {
console.log("Error");
}
})
}
}
In above example we can see that we have used subscribe for subscribing Observable. we use subscribe when we know data will change frequently and we have to keep track on data and when it get change we have to show that data to user.
Say if we know data will not change for example if we send notification to user then it is one time process and after that data will not change. in this type of scenario we use "toPromise".
So when we get data there is no need to listen it or stop subscribing for any data change. simple code shown below:
this.ObservableVarable$.toPromise().then(response => {
console.log("to promise " +response)
}).catch(error => {
console.log("Error")
});
Using Pipe with Angular Observable:
Pipe method from Angular Observable is used to chain multiple operators.
Sample example below:
getPipeWithFilter() {
let arr1$ = of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // Created Observable
let filterData = arr1$.pipe(
filter(x => x % 2 === 0),
reduce((acc, one) => acc + one, 0)
)
filterData.subscribe(x => console.log(x));
}
Example for Using map with Pipe
let testMap = arr1$.pipe(
map(val => { return val * 2}
)).subscribe(val => { console.log(val)});
Example for Using Tap with Pipe
Tap is on of RxJS operator that return an observable that is identical to the source. Tap will not modify the stream, it is useful for logging the value or debugging.
let testTap = arr1$.pipe(
tap(val => {
console.log("Tap " + val);
}),
map(val => { return val * 2}
)).subscribe(val => { console.log(val)});
Comments
Post a Comment