简体   繁体   中英

Async pipe in Angular

Im currently going through the getting started section in Angular, and there is one part which I don't understand.

From the cart-service they're getting Data from a shipping.json in the app-folder.

HttpClient http;

getShippingPrices() {
return this.http.get('/assets/shipping.json');
}

Then in the shippingComponent they're calling the method:

 ngOnInit() {
this.shippingCosts = this.cartService.getShippingPrices();

And in the html-template the async pipe has to be used.

   <div class="shipping-item" *ngFor="let shipping of shippingCosts | async">

I don't understand, why do we have to use the async pipe?

Or can it be done without the async pipe?

You are using async pipe only when you are not subscribed to the observable. Its the most recommended way of getting the data since you dont have to unsubscribe once the data is gone, it will do automatically. As you can see in this code you dont have subscribe to the cartService.getShippingPrices();

ngOnInit() {
  this.shippingCosts$ = this.cartService.getShippingPrices();
}
<div class="shipping-item" *ngFor="let shipping of shippingCosts$ | async">{{ shipping }}</div>

In this code you will get the same result but without async pipe, but remember in this case you will have to subscribe to the cartService.getShippingPrices(). Also once you are done with the data in this particular case you will have to unsubscribe from the observable.

shippingCosts;
ngOnInit() {
  this.cartService.getShippingPrices().subscribe((data) => this.shippingCosts = data);
}
<div class="shipping-item" *ngFor="let shipping of shippingCosts">{{ shipping }}</div>

Another important note: Please add the dollar sign in front of the variable that is holding the observable. Using the dollar sign in the name of a variable that is an observable, is considered best practice. This way it's easy to identify if your variable is an observable or not.

Example: shippingCosts$

Words from the Angular documentation :

The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.

And again from Angular documentation :

Angular makes use of observables as an interface to handle a variety of common asynchronous operations. For example:

  • You can define custom events that send observable output data from a child to a parent component.
  • The HTTP module uses observables to handle AJAX requests and responses.
  • The Router and Forms modules use observables to listen for and respond to user-input events.

So why would you want to avoid using the async pipe? Just use it over your app and get delighted by reactive programming capabilities ;)

Because http.get return with an Observable object, not with the data. If you don't want to use async pipe, you can subscribe or use await.

this.shippingCosts = await this.cartService.getShippingPrices().first().toPromise();

A typical async or observable operation requires a subscription or an await construct like this:

// async await example
async function getPrices(){
  let prices = await this.cartService.getShippingPrices();
  return prices;
}

This code using the async/await construct does not return until after the code has completed. "let prices = await" is the signature for what is called a closure, it's functionally the same thing as:

ngOninit(({
  //subscription on observable example
  getPrices.subscribe(prices=>{ //data returned here });
}
function getPrices(){
  this.cartService.getShippingPrices();      
}

As you can see in both cases the result is prices. Using the async pipe, the code automatically hooks up to the result at some point in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM