5

Błąd: Uncaught (obietnicy): TypeError: nie można ustawić właściwość 'isAdmin' null

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

Dostaję błąd na linii nr 8

Error: Uncaught (in promise): TypeError: Cannot set property 'isAdmin' of null

Proszę o pomoc!

Odpowiedz

7

Albo można użyć funkcji strzałki

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

lub użyj

var self = this; 

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

inaczej this nie wskazuje aktualną funkcję kiedy to się nazywa.

Zobacz także https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions

+1

Ta odpowiedź jest poprawna. Zakres 'this' zmienia się wewnątrz wywołania zwrotnego bazy danych Firebase, więc musisz właściwie zachować referencję. –

+1

Dzięki! To rozwiązało mój problem! –

+0

@Gunter Czy masz stronę o kątowym 2 Czy mogę przeczytać o tym "zakresie? – crh225

Powiązane problemy