简体   繁体   English

firebase 或 firebase auth 中的 onAuthStateChanged() 不返回值

[英]onAuthStateChanged() in firebase or firebase auth does not return values

i'm using angular with firebase authentication.我正在使用 angular 和 firebase 身份验证。 when i use onAuthStateChanged method to know if the user is logged in or not it does not return the user or even with angularfireAuth.currentUser when i want to retrieve the user data it's giving me this error: for example i used afAuth.currentUser.uid to use it in my query functions当我使用 onAuthStateChanged 方法来了解用户是否已登录时,它不会返回用户,甚至不会返回用户,甚至使用 angularfireAuth.currentUser 当我想检索用户数据时,它会给我这个错误:例如,我使用了 afAuth.currentUser.uid在我的查询函数中使用它

Uncaught (in promise): TypeError: Cannot read property 'uid' of null未捕获(承诺):TypeError:无法读取 null 的属性“uid”

this is the code i call in my authService's Constructor:这是我在 authService 的构造函数中调用的代码:

 firebase.auth().onAuthStateChanged(firebaseUser => {
          if (firebaseUser) {
            console.log(firebaseUser.uid)
            this.user.next(firebaseUser)
            return (firebaseUser.uid)
          } else {
            return (null)
          }
    })

I think i have to do it asynchronously but i don't know how?我想我必须异步执行,但我不知道怎么做? Any Ideas?有任何想法吗?

Since you are using angularfire, I would suggest you listen to authState .由于您使用的是 angularfire,我建议您听authState I see that you are exposing an observable, subject of some kind, since you are calling next .我看到您正在公开某种可观察的主题,因为您正在调用next But I would assign the value from authState to an observable, which you can subscribe to to get realtime changes, as this is triggered whenever changes happen to the authState .但是我会将authState中的值分配给一个 observable,您可以订阅它以获取实时更改,因为每当authState发生更改时都会触发该值。

Service:服务:

import { User } from 'firebase';

// ...

user$: Observable<User | null>;

constructor(
    private afAuth: AngularFireAuth
) {
    this.user$ = this.afAuth.authState;
}

Then in your components you can subscribe to user$ :然后在您的组件中,您可以订阅user$

this.myService.user$.subscribe(....)

Here though you need to remember to unsubscribe when component is destroyed!!在这里,尽管您需要记住在组件被销毁时取消订阅!

You can also write a function in the service, that returns the user once, and you don't need to worry about unsubscribing.也可以在服务中写一个function,一次返回用户,不用担心退订。

In service same code as above, but add:在服务中与上面相同的代码,但添加:

getUser() {
  return this.user$.pipe(first())
}

Now when in components you subscribe to this function, your user is just emitted once.现在,当您在组件中订阅此 function 时,您的用户只会发出一次。

If you need to use this user in some other async function that depends on for example the uid , you can chain these requests using switchMap ormergeMap .如果您需要在其他依赖于uid的异步 function 中使用此用户,您可以使用switchMapmergeMap链接这些请求。 So what you can do is...所以你能做的就是...

this.myService.getUser().pipe(
  switchMap((user: User) => {
    return this.getCat(user.uid)
  })
// will console true or false
).subscribe(data => console.log(data))

Are you wrapping that code in to a function and calling that function when the page loads?您是否将该代码包装到 function 并在页面加载时调用该 function ? Maybe try wrapping it in a function and calling the loginStatus function when the page first loads也许尝试将其包装在 function 并在页面首次加载时调用 loginStatus function

function loginStatus() { 
    firebase.auth().onAuthStateChanged(firebaseUser => {
      if (firebaseUser) {
        console.log(firebaseUser.uid)
      this.user.next(firebaseUser)
      return (firebaseUser.uid)
    } else {
      return (null)
    }
  })
}

If you are using angularFire you can import AngularFireAuth from @angular/fire/compat/auth and do the following in your component:如果您使用angularFire ,您可以从@angular/fire/compat/auth导入AngularFireAuth并在您的组件中执行以下操作:

constructor(
  private afa: AngularFireAuth
) { }

ngOnInit(): void {
  this.monitorAuthState()
}

private monitorAuthState = async () => {
  this.afa.onAuthStateChanged( user => {
    if(user) { console.log(user) }
  })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 firebase.auth()。onAuthStateChanged返回什么? - what is returned on firebase.auth().onAuthStateChanged? 如何从firebase.auth()。onAuthStateChanged中提取数据 - How to extract the data from a firebase.auth().onAuthStateChanged Firebase:如何从 firebase.auth().onAuthStateChanged 异步绑定用户到 Angular 模板? - Firebase: How to asynchronously bind User from firebase.auth().onAuthStateChanged to Angular template? Angular 组件模板不会随着 firebase onAuthStateChanged 接收到的事件而更新 - Angular component template does not update with events received by firebase onAuthStateChanged firebase 和 auth 属性在 Ionic 和 Firebase 中不存在 - firebase and auth property does not exist in Ionic and Firebase AuthGuard:Angular 5 + Firebase 中的 OnAuthStateChanged VS 检查令牌 - AuthGuard: OnAuthStateChanged VS check token in Angular 5 + Firebase 斐波那契数列之后,firebase onAuthStateChanged - firebase onAuthStateChanged following Fibonacci's series Firebase EmailPasswordAuthProvider 在类型身份验证中不存在 - Firebase EmailPasswordAuthProvider Does Not Exist on Type Auth 为什么firebase.auth().currentUser即使用户登录也返回NULL - Why does firebase.auth().currentUser return NULL even when the user is logged in 如何使用Firebase的onAuthStateChanged来跟踪Angular中的用户登录状态? - How to use Firebase's onAuthStateChanged to track user login state in Angular?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM