How To Use Observable In Angular?
This Article helps you to Understand, How To Use Observable In Angular?
The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of state changes. This pattern is similar (but not identical) to the publish/subscribe design pattern.
Angular Observables facilitate sending messages between publishers (Observable Creators) and subscribers (Observable Users). Since observables are declarative, the function for publishing values is defined, but it is not used until a consumer subscribes.
Depending on the context, the observable may return numerous values of any type, including literals, messages, or events. As a publisher, you can create an Observable instance that defines a subscriber function. This function is executed when the consumer calls the subscribe() method.
To create an Observable in Angular, first it is necessary to import Observable from rxjs
To create a new Observable we just need to use its constructor and to add the logic that will be executed upon subscription.
Lets understand with a complete example
Create a service
In this observable example we are going to make the search function that return an observable which the AppComponent is going to subscribe. The return type is ObservableSearchItem[]>, and it will return an observable with an array of SearchItems as each item, with each item in the observable being a SearchItem.
By default, the http.get(...) function returns an Observable; more precisely, it returns an Observable of Response types, in which case the type would be ObservableResponse>. We just return that in its place.
Consequently, we must translate the raw JSON into our SearchItem model. We must essentially turn the Response into an array of SearchItems. We can accomplish that with our Observable by using a map operation to turn each Response into an array of SearchItems.#2 map is an observable operator which calls a function for each item on its input stream and pushes
#3 We loop over each item in the results property of the Response object and transform the item via a function.
#4 We convert the raw data returned from our API into an instance of SearchItem
Subscribing - One way to use above Observable in our Component would be just to subscribe to it and store the results locally,
Using the async Pipe
Although the aforementioned is a nice beginning, we are not really utilising Observables to their full potential because, among other things, we are subscribing to the observable and storing the results locally on the component. We can avoid doing this by simply using the async pipe in our template.
Lets create another observable to create Auto-search Input box
Let's modify our programme so that it utilises a reactive form and searches as we write.
Through a chain of operators we want to convert that Observable<string> into an Observable<SearchItem[]>.
#3 We call the search service for every emit of a search term on the input stream.
lets check our Logs
What’s happening is that items.search(term) isn’t returning SearchItem[] it’s returning Observable<SearchItem[]>.So instead of converting a string to a SearchItem[], the map operator really converts a string to an ObservableSearchItem[]>.
Thus, instead of receiving SearchItem[] as we would like, the subscribe method is receiving ObservableSearchItem[]>.
Approach 1: using another subscriber
#2 Second subscribe again on each of these observables to get the SearchItem[].
Approach 2: use switch
switch expects a stream of Observables,
switch unsubscribes from any current Observables and subscribes to the new one when an Observable is pushed onto its input stream. It then emits any values from that Observable onto its output stream.
There is a combination operator called switchMap since combining switch with map is so popular.
Loading Indicator
The last step is to add the loading boolean to the chain and use the do operator to set it to true and false at the appropriate moments so that the loading message appears as intended.
The do operator allows us to do things other than merely manipulate objects via streams, so we utilise it in our programme to generate side effects. It should only be used sparingly, but in this case, setting the state of our component according to where we are in the processing chain, is a perfect illustration.