为什么我的函数没有返回所需的值?

时间:2021-06-01 22:01:20

标签: angular typescript ionic-framework google-cloud-firestore firebase-authentication

当我从其他地方调用该函数时,它没有返回所需的值,问题是它在执行该函数之前返回了一个未定义的值,它可以工作,我将它存储在服务中。

登录.page.ts:

ngOnInit(){
  console.log(this.auth.getRole());
}

auth-admin.service.ts:

第一次尝试

getRole() {
     this.afAuth.onAuthStateChanged(user => {
       if (user) {
         this.afs.firestore.doc(`Core/Usuarios/Admin/${user.uid}`)
         .get()
         .then(userProfileSnapshot => {
           let isAdmin = userProfileSnapshot.data().udbid.role;
           return isAdmin;
         })
       }
     });
   }

控制台日志

<块引用>

未定义

在我的第二次尝试中,我在返回值之前放置了一条控制台消息,这在我的控制台中为我提供了所需的值,但在给我一个未定义的值后的一段时间内执行了此操作,但该函数从未应用返回值。

第二次尝试

 getRole() {
     this.afAuth.onAuthStateChanged(user => {
       if (user) {
         this.afs.firestore.doc(`Core/Usuarios/Admin/${user.uid}`)
         .get()
         .then(userProfileSnapshot => {
           let isAdmin = userProfileSnapshot.data().udbid.role;
           console.log(isAdmin)
           return isAdmin;
         })
       }
     });
   }
   

控制台日志:

<块引用>

未定义

管理员

1 个答案:

答案 0 :(得分:0)

尝试使您的 getRole 函数异步。