简体   繁体   中英

Angular async pipe hangs on a promise

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?

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>

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