简体   繁体   English

使用Firebase,即使正在记录firebase.auth()。currentUser,它也是一个空值

[英]Using Firebase, firebase.auth().currentUser is a null value even though it is being logged

I created a query that is in a service.TS file that shows an items "state" that is based on a logged in user's UID: 我在service.TS文件中创建了一个查询,该查询显示了基于登录用户的UID的项“状态”:

getLists(): FirebaseListObservable<any> {

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {console.log("blah", firebase.auth().currentUser.uid)
    // User is signed in.
  }
});
  return this.db.list('/foods', {
    query: {
      orderByChild: 'state/'+firebase.auth().currentUser.uid+'/state',
      equalTo: 'listed'
    }
  });
}

Using this query, I'm getting an error that reads: 使用此查询,我收到一条错误消息:

Uncaught (in promise): TypeError: null is not an object (evaluating ' WEBPACK_IMPORTED_MODULE_2_firebase_app "auth".curren‌​tUser.uid'). 未捕获(承诺):TypeError:null不是对象(评估为' WEBPACK_IMPORTED_MODULE_2_firebase_app “ auth” .curren‌tUser.uid')。

Using {console.log("blah", firebase.auth().currentUser.uid) , which you can see above, correctly displays the UID in the log, confirming that the user is signed in. 使用上面可以看到的{console.log("blah", firebase.auth().currentUser.uid) ,在日志中正确显示UID,确认用户已登录。

I'm not sure if it's relevant but this query is being called by the page's main TS file with: 我不确定是否相关,但是页面的主要TS文件通过以下方式调用了此查询:

    ngOnInit() {

    this.moviesSvc.getLists()
                  .subscribe(lists => {console.log(lists); console.log("UID", firebase.auth().currentUser.uid); this.lists = lists})
  }

What do I need to do to correctly pass the UID to the query? 我需要怎么做才能正确地将UID传递给查询?

onAuthStateChanged() is asynchronous, so when you have the user uid in its callback, then only perform your operation, like this: onAuthStateChanged()是异步的,因此,当用户uid在其回调中时,则仅执行操作,如下所示:

getLists(): FirebaseListObservable<any> {

    var self = this;

    firebase.auth().onAuthStateChanged(function(user) {
        if (user) {
            // User is signed in.
            var userID = user.uid;

            return self.db.list('/foods', {
                query: {
                    orderByChild: 'state/' + userID + '/state',
                    equalTo: 'listed'
                }
            });
        }
    });

}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM