如何从函数获得值与打字稿(ionic2)
问题描述:
我试图从函数中获取值。这就是我正尝试做:如何从函数获得值与打字稿(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)
});
}
我在做什么错了?
答
由于TheFallen评论说你需要返回一个承诺。始终使用承诺或您会遇到问题。试试这个
getUserFavsCount = (userId: string): Promise<number> => {
// SINCE YOU RETURN A LENGTH, THEN THE PROMISE SHOULD RETURN A NUMBER
// THERE'S NO NEED TO DECLARE A COUNT VARIABLE SINCE YOU'LL NOT USE IT
return new Promise<number>(resolve =>{
let favs = this.af.list(`/favorites/${userId}`).subscribe(data =>{
resolve(data.length);
});
});
}
,然后让你的数据
countUserFav() {
this.userProvider.currentUser.first().subscribe((currentUser: User) => {
this.favoriteProvider.getUserFavsCount(currentUser.$key).then(res =>{
this.myFavs = res;
});
});
}
希望这有助于:d
你必须归还从'getUserFavsCount()一个承诺'因为你正在做一个请求火力地堡并且只有当请求完成后,你才会有实际的计数。所以你可以从'getUserFavsCount'中返回'this.af.list('/ favorites/$ {userId}')'并在'countUserFav'中订阅它,并且只有当它准备好更新'this.myFavs'时。 – TheFallen
TheFallen,谢谢!有用 :) –