An observable is a sequence of items that arrives asynchronously over time. This tutorials explains the concepts of observables in Angular and how they are used in Angular applications. When we discuss about Angular Observable we keep following things in mind Reactive programming, data streams, Observable, Observers, RxJS etc. So it is very important to understand in brief these things before using observables in angular.
Example
Here is a real-world example from that we can understand concept of observables in better way. You may think about newspaper where subscribers receive newspaper while non-subscribers do not. The below image show observable concept.
In the above image,
In the above scenario:
What is RxJS?
RxJS stands for Reactive Extensions for JavaScript. It is a library that makes it possible for us to work with these streams of data. In RxJS, the Observer is an Object with 3 built-in methods. The Houses are the Observer and the newspaper that's streaming is the Observable. Being the Observer, you can get three different notifications: next, error, and complete.
Import the Observable from the rxjs library.
import { Observable } from 'rxjs';
There are few points which are useful to understand promise in better way.
1. Observable emits multiple value at a time
The below example show that firstly we have create object of Observable and define the values First, Second and Third.
// Observable Emits multiple values
const multipleValueObservables = new Observable((observer) => {
observer.next('First');
observer.next('Second');
observer.next('Third');
});
multipleValueObservables.subscribe((value) => console.log("multiple values :" + value));
The above example will produce multiple value at a time.
2. Observable executes only when someone is subscribing
It will execute when it is called or subscribing to that observable. The below example defines how to subscriber.
// Observable - Executes only when it is called or someone is subscribing
const observable = new Observable(() =>
console.log(`Observable is called`)
);
observable.subscribe();
The above example will produce following output.
3. Observable can be cancellable
It can be cancellable when we unsubscriber it.
//Observable - Can be cancellable
const cancellableObservables = new Observable((observer) => {
setInterval(() => {
observer.next('First');
observer.next('Second');
observer.next('Third');
}, 1000);
});
const cancellableSubscription = cancellableObservables.subscribe((value) => console.log("multiple values :" + value));
cancellableSubscription.unsubscribe();
The above code will not produce any output.
4. Observable possibly asynchronous
//Observable possibly asynchronous
const possibleAsyncObservable = new Observable((observer) =>
observer.next(5)
);
possibleAsyncObservable.subscribe((value) =>
console.log("Possible Async observable:" + value)
);
6. Handling an HTTP request with an Observable in Angular
Let's now see how to use Observable in Angular to work with HTTP asynchronously. we will learn that with a example.
import { Component } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import { Observable } from 'rxjs';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'ObservableApp';
constructor(private httpClient: HttpClient) {
}
ngOnInit() {
this.getemployee().subscribe(res => {(res as []).forEach((data: any) => {
console.log(JSON.stringify(data));
})
}
);
}
getemployee() {
return this.httpClient.get('https://localhost:44340/api/employee');
}
}
Add the following code in App.Module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule, HttpClient } from "@angular/common/http";
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Now run the applicatyion and check browser console.
Now run the over all code to understand Observable better way.
import { Component } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import { Observable } from 'rxjs';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'ObservableApp';
constructor(private httpClient: HttpClient) {
}
ngOnInit() {
//Observable - Can be cancellable
const cancellableObservables = new Observable((observer) => {
setInterval(() => {
observer.next('First');
observer.next('Second');
observer.next('Third');
}, 1000);
});
// Observable - Executes only when it is called or someone is subscribing
const observable = new Observable(() =>
console.log("Observable is called")
);
observable.subscribe();
// Observable Emits multiple values
const multipleValueObservables = new Observable((observer) => {
observer.next('First');
observer.next('Second');
observer.next('Third');
});
multipleValueObservables.subscribe((value) => console.log("multiple values :" + value));
//Observable possibly asynchronous
const possibleAsyncObservable = new Observable((observer) =>
observer.next(5)
);
possibleAsyncObservable.subscribe((value) =>
console.log("Possible Async observable:" + value)
);
const cancellableSubscription = cancellableObservables.subscribe((value) => console.log("multiple values :" + value));
cancellableSubscription.unsubscribe();
this.getemployee().subscribe(res => {(res as []).forEach((data: any) => {
console.log(JSON.stringify(data));
})
}
);
}
getemployee() {
return this.httpClient.get('https://localhost:44340/api/employee');
}
}
Output