Dmitry Chernyak
Dmitry Chernyak

Reputation: 305

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)
  });
}

}

Upvotes: 0

Views: 688

Answers (1)

Chaka15
Chaka15

Reputation: 1371

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.

Upvotes: 3

Related Questions