Observable in Angular is a feature that provides support for delivering messages between different parts of your single-page application. This feature is frequently used in Angular because it is responsible for handling multiple values, asynchronous programming in Javascript, and also event handling processes.
In this simple example we'll call an api recieve an Observable and just console.log it out.
Just before that let us brush up two concepts
- What is Observable?
Observable is a function that converts the ordinary stream of data into an observable stream of data. You can think of Observable as a wrapper around the ordinary stream of data.
Observable stream or simple Observable emits the value from the stream asynchronously. It emits the complete signals when the stream completes or an error signal if the stream errors out.
Observables are declarative. You define an observable function just like any other variable. The observable starts to emit values only when someone subscribes to it.
- What are observers/subscribers?
The observers are the ones which consumes the value emitted by the observable, these are called observers or subscribers.
The observer must subscribe with the observable to receive the value from the observable. While subscribing it optionally passes the three callbacks. next(), error() & complete()
Creating an Observables
obs = new Observable((observer) => {
console.log("Observable starts")
observer.next("1")
observer.next("2")
observer.next("3")
observer.next("4")
observer.next("5")
})
Subscribing to it
this.obs.subscribe({
next: (v) => console.log(v),
error: (e) => console.error(e),
complete: () => console.info('complete')
})
*Returning an observable and subscribing it during an API call
*
catAPI() {
return this.http.get<Observable<any>>('https://catfact.ninja/fact')
}
callingCatAPI(){
return this.catAPI().subscribe( val => {
console.warn(val);
})
}
Top comments (0)