2017-03-07 72 views
1

我正在尋找的僞代碼如下,但它導致我的瀏覽器掛起。如何在Angular2模板中顯示異步承諾函數的結果?

index.ts

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

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

的index.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

+0

你的代碼應該可以正常工作。如果它不請添加代碼'puchServe.findCustomerById()' –

+0

@GünterZöchbauer我已經添加了'findCustomerById' –

+0

瀏覽器控制檯是否顯示任何錯誤? –

回答

1

@Component()刪除

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

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

更新

getCustomerNameById('1') | async調用getCustomerNameById()反覆,甚至掛起我的瀏覽器。
getCustomerById()(Promise或實際值)的結果分配給屬性並將其綁定到該屬性會更好。

綁定到每次調用時都會返回一個新值的方法在Angular2中通常是一個壞主意。

Plunker example

+0

這沒有幫助,它和以前一樣 –

+0

我更新了我的答案。 –

+0

其實我不能綁定到一個屬性,因爲僞函數getCustomerNameById所帶的參數是不同的。 –