Angular async pipe hangs on a promise

AK_

this is a snippet of my template:

<div class="explanation">
 {{ foo() | async }}
</div>

this is the function:

  foo(): Promise<string> {
    return Promise.resolve('hello');
  }

This just hangs the browser. How come? what am i missing?

SiddAjmera

From MDN on Promise.resolve

Warning: Do not call Promise.resolve on a thenable that resolves to itself. This will cause infinite recursion as it tries to flatten what seems to be an infinitely nested promise.

AND

From Angular's Avoid side effects guideline:

evaluation of a template expression should have no visible side effects. The expression language itself does its part to keep you safe. You can't assign a value to anything in a property binding expression nor use the increment and decrement operators.

Your implementation seems to do just that.

Fix:

As suggested by wannadream, assign the promise to a property and then use that property in the template along with the async pipe:

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

@Component({...})
export class AppComponent  {
  foo: Promise<string>;

  ngOnInit() { 
    this.foo = Promise.resolve('hello'); 
  }
}

And in the template:

<div class="explanation">
  {{ foo | async }}
</div>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related