【问题标题】:Using Firebase, firebase.auth().currentUser is a null value even though it is being logged使用 Firebase,firebase.auth().currentUser 是一个空值,即使它正在被记录
【发布时间】:2018-03-05 21:06:27
【问题描述】:

我在 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'
    }
  });
}

使用此查询,我收到一条错误消息:

未捕获(承诺中):TypeError: null 不是对象(评估 'WEBPACK_IMPORTED_MODULE_2_firebase_app"auth".curren‌​tUser.uid')。

使用上面可以看到的{console.log("blah", firebase.auth().currentUser.uid),在日​​志中正确显示UID,确认用户已登录。

我不确定它是否相关,但页面的主 TS 文件正在调用此查询:

    ngOnInit() {

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

我需要做什么才能正确地将 UID 传递给查询?

【问题讨论】:

    标签: javascript angular typescript firebase-realtime-database firebase-authentication


    【解决方案1】:

    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'
                    }
                });
            }
        });
    
    }
    

    【讨论】:

    • 这给了我一个错误显示:声明类型既不是“void”也不是“any”的函数必须返回一个值。我也收到错误:TypeError: undefined is not an object (evalating 'this.db.list')Uncaught (in promise): TypeError: undefined is not an object (评估 'this.movi​​esSvc.getLists() .subscribe').
    • @cfoster5 更新了代码,回调里面的'this'会有所不同,所以将其缓存为self并使用它..
    • 尝试这个仍然会出现上面列出的错误。
    猜你喜欢
    • 2017-12-06
    • 2020-09-26
    • 2017-01-04
    • 2017-10-04
    • 2021-09-16
    • 2018-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多