0
我試圖從函數中獲取值。這就是我正嘗試做:如何從函數獲得值與打字稿(ionic2)
在文件favorite.ts
getUserFavsCount(userId: string){
let count = 0;
let favs = this.af.list(`/favorites/${userId}`).subscribe(data =>{
count = data.length;
});
console.log(count) // getting the value. here it shows correct
return count;
}
現在,在我的profile.ts我正嘗試獲取該值:
countUserFav() {
this.userProvider.currentUser.first().subscribe((currentUser: User) => {
console.log("---->",this.favoriteProvider.getUserFavsCount(currentUser.$key)); // here I get 0 value always :(
this.myFavs = this.favoriteProvider.getUserFavsCount(currentUser.$key)
});
}
我在做什麼錯了?
你必須歸還從'getUserFavsCount()一個承諾'因爲你正在做一個請求火力地堡並且只有當請求完成後,你纔會有實際的計數。所以你可以從'getUserFavsCount'中返回'this.af.list('/ favorites/$ {userId}')'並在'countUserFav'中訂閱它,並且只有當它準備好更新'this.myFavs'時。 – TheFallen
TheFallen,謝謝!有用 :) –