2017-03-16 35 views
0

我有項目列表,並希望通過api調用加載每個項目的一個值。Ionic 2:懶惰加載列表的項目值

問題:Api調用函數(即getCount(value))被調用無限次。

這個簡單的代碼說明我的問題:

模板文件代碼:

<ion-item *ngFor="let item of items"> 
    {{getCount(item.value) | async}} 
    </ion-item> 

TS文件代碼:

export class LognPage { 
    public items = [{ value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }, { value: 5 }, { value: 6 }]; 

    getCount(value) { 
    new Promise((reject, resolve) => { 
     setTimeout(() => { 
     resolve("value " + value); // this is called infinite number of times 
     }, 2000); 
    }); 
    } 
} 

有誰提供任何幫助嗎?

什麼是無限呼叫的原因,我不能這樣做嗎?

回答

0

不要在你的模板中使用函數:

valueList : Promise<any[]> 

ngOnInit(){ 

    for(item of items){ 
    getCount(item).then((value)=>{ 
     valueList.push(value); 
    }) 
    } 

} 



getCount(value) { 
    new Promise((reject, resolve) => { 
     setTimeout(() => { 
     resolve("value " + value); // this is called infinite number of times 
     }, 2000); 
    }); 
    } 

HTML:

<ion-item *ngFor="let value of valueList"> 
    {{value }} 
    </ion-item>