简体   繁体   中英

What is AsyncPipe and examples to use

I need your help. I'm trying to study the angular in more detail and got to asyncPipe. I have this example, but I don't know how it works. Can you please explain how this code works in detail? Thank you very much

import {Component, OnInit} from '@angular/core';

@Component({
selector: 'app-root',
template: `
    <p *ngIf="($observable | async) as time">
  Current Timer Value {{time}}
    </p>`,
styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit{'

$observable: Promise<any>

ngOnInit(): void {
  this.$observable = new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('foo')
    },3000)
  });
}

}

In simple terms async pipe subcscribes to an observable, "unpacks" its data and takes care of unsubscribing. It is considered better practice than manually calling .subscribe() and in ngOnDestroy() calling .unsubscribe() .

When we use async pipe we don't have to worry about above mentioned things.

In your example you faked an API call in ngOnInit lifecycle method and you want to display data you got from that call in .html file. Additionally, this as in your template just makes a template variable that you used below.

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