错误:未捕获(在承诺中):TypeError:无法将属性'isAdmin'设置为null

Ank*_*ari 6 firebase firebase-authentication firebase-realtime-database angular

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;
  }
});
Run Code Online (Sandbox Code Playgroud)

我在第8行遇到错误

错误:未捕获(在承诺中):TypeError:无法将属性'isAdmin'设置为null

Gün*_*uer 11

要么你可以使用箭头功能

firebase.database().ref('/userProfile/' + user.uid).once('value')
.then((snapshot) => {
Run Code Online (Sandbox Code Playgroud)

或使用

var self = this;

firebase.database().ref('/userProfile/' + user.uid).once('value')
.then(function(snapshot) {
   self.isAdmin = true;
Run Code Online (Sandbox Code Playgroud)

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

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