【问题标题】:Error: Uncaught (in promise): TypeError: Cannot set property 'isAdmin' of null错误:未捕获(承诺中):TypeError:无法设置属性“isAdmin”为空
【发布时间】:2016-12-12 22:56:27
【问题描述】:
firebase.auth().onAuthStateChanged((user) => {
  if(user) {
    this.isLoggedIn = true; //Set user loggedIn is true;
    this.isAdmin = false;
    firebase.database().ref('/userProfile/' + user.uid).once('value').then(function(snapshot) {
      let userInfo = snapshot.val();
      if(userInfo.isAdmin == true) {
        //ERROR AT THIS LINE: 
        //Error: Uncaught (in promise): TypeError: Cannot set property 'isAdmin' of null
        this.isAdmin = true;
        console.log(userInfo);
      }
    });
  } else {
    this.isLoggedIn = false; //Set user loggedIn is false;
  }
});

我在第 8 行遇到错误

错误:未捕获(承诺中):TypeError:无法设置属性“isAdmin”为空

【问题讨论】:

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


    【解决方案1】:

    你可以使用箭头功能

    firebase.database().ref('/userProfile/' + user.uid).once('value')
    .then((snapshot) => {
    

    或使用

    var self = this;
    
    firebase.database().ref('/userProfile/' + user.uid).once('value')
    .then(function(snapshot) {
       self.isAdmin = true;
    

    否则this 在调用时不会指向当前函数。

    另见https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions

    【讨论】:

    • 这个答案是正确的。 this 范围在 Firebase 数据库回调中发生变化,因此您需要正确保留引用。
    • @Gunter 你有关于 Angular 2 的页面吗?我可以阅读关于这个范围的信息吗?
    • 查看我添加到答案中的链接。这是一个古老的 JS 问题。
    猜你喜欢
    • 1970-01-01
    • 2018-06-11
    • 1970-01-01
    • 2019-06-19
    • 1970-01-01
    • 2018-05-10
    • 2016-12-09
    • 2019-07-18
    • 2021-04-18
    相关资源
    最近更新 更多