InterviewSolution
| 1. |
What is the role AsyncPipe in Angular? |
|
Answer» Simply put, the AsyncPipe allows us to render asynchronous data. The async pipe subscribes to an Observable or Promise and returns the latest value as emitted by the promise or observable. When the component gets DESTROYED, the async pipe unsubscribes automatically to AVOID potential memory leaks. With AsyncPipe we can use promises and observables directly in our template, without having to store the result on an intermediate property or variable. AsyncPipe ACCEPTS as argument an observable or a promise, calls subscribe or attaches a then handler, then waits for the asynchronous result before passing it through to the caller. Consider the following example. my-component.html <span>Wait for it... {{ greeting | async }}</span> my-component.ts export CLASS MyComponent { greeting: Promise<string>|null = null; constructor() { this.reset(); } reset() { this.greeting = new Promise<string>((RESOLVE, reject) => { this.resolve = resolve; }); }In the above example, the greeting property is not available immediately to the template and thus rendering it out can lead to unpredictable consequences. The Async pipe unwraps the value of the promise as it is returned and then renders it out. This only happens when the value of available. |
|