concept async in category angular

appears as: sync, async
Angular Development with Typescript, Second Edition

This is an excerpt from Manning's book Angular Development with Typescript, Second Edition.

  • An AsyncPipe unwraps the data from the provided Observable stream by using | async. You’ll see a code sample that uses async in section 6.5 in chapter 6.
  • As explained in appendix D, to start getting data from an observable, we need to invoke the subscribe() method. In listing 6.5, there’s no explicit invocation of subscribe(), but note the async pipe in the template. The async pipe autosubscribes to the numbers observable and displays the numbers from 0 to 9 as they’re being pushed by the observable. To see this example in action, run the following command:

    The next listing shows an app component that gets the ProductService injected and invokes getProducts(), which returns an observable. Note that there’s no explicit invocation of subscribe() there—you use the async pipe in the template. In this component, you use Angular’s structural directive *ngFor to iterate through products and for each product render the <li> element with the product title and price, as you can see in the following listing.

    Listing 6.7. asyncpipe-products/app.component.ts
    import {Component} from '@angular/core';
    import {Product, ProductService} from "./product.service";
    import {Observable} from "rxjs";
    
    @Component({
      selector: "app-root",
      template: `
           <ul>
             <li *ngFor="let product of products$ | async">     #1
                {{product.title}} {{product.price}}             #2
              </li>
           </ul>
        `
    })
    export class AppComponent {
    
      products$: Observable<Product[]>;                         #3
    
      constructor(private productService: ProductService) {}
    
      ngOnInit() {
    
        this.products$ = this.productService.getProducts();     #4
       }
    }

    It’s important to understand that the getProducts() function returns an empty observable that hasn’t emitted anything yet, and you assign it to the products$ variable. No data is pushed to this component until you subscribe to products$, and the async pipe does it in the template.

  • Using the async pipe is a preferable way to subscribe to observables.
  • The async pipe automatically unsubscribes from the observable.