如何在 Angular2 模板中显示异步 Promise 函数的结果?

Moh*_*kar 5 typescript angular

我正在寻找的伪代码如下所示,但它导致我的浏览器挂起。

索引.ts

findCustomerById(id) {
    return new Promise<string>((resolve, reject) => {
        resolve("hi");
    });
}

getCustomerNameById(id: string) {
    return this.findCustomerById(id);
    //findCustomerById returns NEW Promise<string>
}
Run Code Online (Sandbox Code Playgroud)

索引.html

<p>Customer: {{ getCustomerNameById('1') | async }} </p>
//this does not show anything

<p>Customer: {{ getCustomerNameById('1') | async | json }} </p>
//this shows null

<p>Customer: {{ getCustomerNameById('1') | json }}</p>
//this shows the following
{
  "__zone_symbol__state": true,
  "__zone_symbol__value": "hi"
}
Run Code Online (Sandbox Code Playgroud)

这是 Plunker :https ://plnkr.co/edit/pAKtCZo0Uog2GFzlj50c

Gün*_*uer 3

消除

pipes: [...],
directives: [...],
Run Code Online (Sandbox Code Playgroud)

@Component()

并添加 imports: [BrowserModule]AppModule@NgModule()

更新

getCustomerNameById('1') | async反复调用getCustomerNameById(),甚至挂起我的浏览器。
最好将getCustomerById()(Promise 或实际值)的结果分配给属性并绑定到该属性。

在 Angular2 中,绑定到每次调用时都返回新值的方法通常是一个坏主意。

笨蛋的例子