What is observables in Angular?
We will first understand the RxJS library before going to the observables in Angular.
What is RxJS?
RxJS is a library for developing asynchronous and event-based applications by using observable sequences.
What is Observable?
It is an invokable collection of values and events. It is defined as a function to push values, and it is not executed until the consumer subscribes to it. The consumer will receive the notifications until the subscription has been unsubscribed.
It provides support for passing messages within the application. It is frequently used in Angular as a technique to handle asynchronous and event-based programming.
Example of observables:
// Import the RxJS namespace
import {Observable} from 'rxjs';
// Implement the method returns the observable
search(userId:string): Observable<UserInfo[]> {
return this.http.get(apiURL?userid= + userId)
}
// Subscribe to the observable method to receive the notification
this.search().subscribe(
(userList: UserInfo[]) => this.users = userList,
(error: any) => this.errorMessage = error
);
Leave a comment