Observables in Angular & Async pipe

Observables in Angular

Observables are used in Angular for a variety of different asynchronous operations. Observable is a special feature proposed for managing async data. Multiple values of data can be emitted using this at different period of time. It is used as an interface to handle the following things:
  • HTTP module uses observable extensively to handle AJAX requests and responses.
  • The Event Emitter class extends observables.
  • The Form Module uses observables to listen and respond to user inputs.
  • The Router module also uses observables to listen and respond to specific routes and parameters.

HTTP

Angular HttpClient class which performs HTTP requests returns observables in all the requests.
Like Http.get() method will return observables as a response. Observables have many advantages:
  • Observables don't change or mutate responses. Series of operators are can be used to transform the values according to our requirement.  Observables provide many powerful operators in Angular like map, foreach, filter, reduce, retry, etc.
  • Using unsubscribe() method we can cancel the request.
  • Requests can be configured to handle progress as well.
  • We can retry for failed requests or responses.
Now we will see an example of how HTTP use observable for requests and response.
First, you need to import the HttpClient module using the following syntax:
import { HttpClient } from '@angular/common/http';

inject HttpClient in the component's constructor
 constructor(private http: HttpClient){}

Now call a method using http.get(URL) method.
getSites(){
   this.http.get(this.someURL + '/sites').subscribe((res)=>{
   this.sites = res.data || res;
});
}

Async Pipe

It unwraps a value from asynchronous primitive. It is subscribed to an observable or promise and will return the latest emitted value. It continuously checks for changes. Whenever a new value is emitted, the pipe marks the component and its view with the latest value. The observable updates the view with time. The async pipe takes care of subscribing the data and unwrap the data when the component gets destroyed.

Async pipe with ngFor
Now we will see an example of how the async pipe works with the ngFor directive. In the same above example if we want to show the sites in UI. In the below HTML code template we can unwrap and subscribe the data when it comes with the ngFor as below:
<ul>
  <li *ngFor="let siteof sites | async">
     Name: {{ site.name }}
</li>
</ul>


Comments