如何在IONIC typescript 中解决此问题?

7uzetpgm  于 2022-12-09  发布在  Ionic
关注(0)|答案(1)|浏览(123)

我有一个问题,在我的typescript代码的离子项目,我试图获得变量的值(this.currentroom)从函数getCurrentRoom()到另一个函数(get user()),但失败了什么问题,这里是我的聊天服务.ts:

public getCurrentRoom()  {
    this.afs.collection('users',ref => ref.where("email", "==", this.currentUser.email)).get().toPromise()
    .then(snapshot => {
      snapshot.forEach(doc => {
        this.currentRoom=JSON.parse(JSON.stringify(doc.data())).room;
        console.log("current room"+this.currentRoom);
      });
  });

  }
   
   public getUsers()
   {
      this.getCurrentRoom();
      console.log("this room"+this.currentRoom);
      return this.afs.collection('users',ref => ref.where("room", "==", this.currentRoom)).valueChanges({ idField: 'uid' }) as Observable<User[]>;

   }
roqulrg3

roqulrg31#

尝试使用asyncawait,这将告诉JavaScript等待异步方法。

public async getCurrentRoom() {
    await this.afs.collection('users', ref => ref.where("email", "==", this.currentUser.email)).get().toPromise()
        .then(snapshot => {
            snapshot.forEach(doc => {
                this.currentRoom = doc.data().room;
                console.log("current room" + this.currentRoom);
            });
        });
}

public async getUsers() {
    await this.getCurrentRoom();
    console.log("this room" + this.currentRoom);
    return this.afs.collection('users', ref => ref.where("room", "==", this.currentRoom)).valueChanges({
        idField: 'uid'
    }) as Observable < User[] > ;
}

相关问题