'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)
});
}
}
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
