如何通过typescript(ionic2)从函数中获取值

时间:2017-07-06 12:17:38

标签: javascript angular typescript ionic2

我试图从函数中获取值。这就是我想要做的:

in file 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;
    
  }

现在,在我的个人资料中,我试图获得这个值:

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)  

    });
  }

我做错了什么?

1 个答案:

答案 0 :(得分:0)

由于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