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

标签 angular typescript

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

索引.ts

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

getCustomerNameById(id: string) {
    return this.findCustomerById(id);
    //findCustomerById returns NEW Promise<string>
}

索引.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"
}

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

最佳答案

消除

pipes: [...],
directives: [...],

来自 @Component()
并添加 imports: [BrowserModule]AppModule@NgModule()
更新
getCustomerNameById('1') | async来电getCustomerNameById()反复甚至挂起我的浏览器。
最好分配 getCustomerById() 的结果( promise 或实际值)到属性并绑定(bind)到该属性。

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

Plunker example

关于angular - 如何在 Angular2 模板中显示异步 promise 函数的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42645432/

相关文章:

javascript - 自定义 Angular 6 Material 日期选择器

angular - 在 WSO2 API Manager 中放置/配置 CORS header Access-Control-Expose-Headers 的位置

javascript - 类型 'subscribe' 上不存在属性 'Promise'

typescript - Mongoose 的 loadClass() 和 TypeScript

arrays - TypeScript 类型化数组的使用

typescript - angular2-google-maps 标记的点击事件

node.js - Angular 2\Node 依赖关系

Angular2 模板 - 使用变量不在此

reactjs - 在 TypeScript 中扩展 React-Native-Paper 组件

typescript - 如何从命令行检查 TypeScript 代码的语法错误?