Friday, August 21, 2020

Observable in Angular

Angular internally uses Observables for different features, which needs to listen to specific sources and trigger actions based on specific events/values. Angular uses Observables for the following.


1.       @Output decorator
Angular provides an EventEmitter class that is used when publishing values from a component through the @Output() decorator. EventEmitter extends RxJS Subject, adding an emit() method so it can send arbitrary values. When you call emit(), it passes the emitted value to the next() method of any subscribed observer.

2.       HttpClient
The HttpClient in Angular is used to make API calls. The http.get() method returns an observable, components can subscribe to the observable or use an Async pipe to consume the response from the API calls.

3.       Async pipe
Async pipe is another way to consume response from http.get(), instead of subscribing to the observable returned from HttpClient, we can just map the observable to the asyn pipe in the view template. Async pipe will automatically subscribe and consume the result from the API call and unsubscribe when all the values are consumed.

4.       Router
The Angular router exposes router events as an observable, we can subscribe to receive route events and get notified whenever a route is invoked. We can use the filter() operator from RxJS to look for events of interest and make decisions based on the sequence of events in the navigation process.

5.       Reactive Forms
Reactive forms have properties that use observables to monitor form control values. The FormControl properties valueChanges and statusChanges contain observables that raise change events. Subscribing to an observable form-control property is a way of triggering application logic within the component class.

Search Flipkart Products:
Flipkart.com

No comments: