2017-08-13 81 views
1

我試圖從Firebase數據庫中獲取項目,但看起來不行。 操作員「這個」不是快照功能工作(上線this.authState.prenom = snapshot.val().prenomAngular 4 + Firebase在請求數據庫時獲取快照值

,如果我這樣做的功能外,似乎它的功能之前執行,因此該屬性是空的。我發現唯一的解決方案是把超時(一行setTimeout(() => this.authState.prenom = prenom,1000)",但它不是我想要的

我只想要聲明this.authState.prenom = prenom;快照功能結束後執行或從任何獲取該快照函數的值在任何。這樣

這裏是我的文件(變量都聲明)

auth.service.ts 這裏是構造函數:

constructor(private afAuth: AngularFireAuth, 
    private db: AngularFireDatabase, 
    private router:Router) { 

this.afAuth.authState.subscribe((auth) => { 
    this.authState = auth; 

    if(this.currentUser){ 
    var userId = this.currentUser.uid; 

    var prenom: any; 
    var nom: any; 

    firebase.database().ref('/users/' + userId).on('value',function(snapshot) { 
     // this.authState.prenom = snapshot.val().prenom; <= This is not working because I can't use "this" operator here and don't know why 

     console.log(snapshot.val().prenom); 
     console.log(snapshot.val().nom); 

     prenom = snapshot.val().prenom; 
     nom = snapshot.val().nom; 

     // this.authState.nom = snapshot.val().nom; <= not working because of the operator "this" 
    }); 
    this.authState.prenom = prenom // <= Not working because it's executed before the snapshot function and don't know why 
    setTimeout(() => this.authState.prenom = prenom,1000); // <= This is working but setting timeout is not a good thing.. 
    setTimeout(() => this.authState.nom = nom,1000); 
    // console.log(this.authState.prenom); 
    } 
} 

回答

0

要獲得this工作,動用脂肪箭頭函數符號(如你與auth.subscribe做):

firebase.database().ref('/users/' + userId).on('value', (snapshot) => { 
    this.authState.prenom = snapshot.val().prenom; 
    this.authState.nom = snapshot.val().nom; 
}); 

一些較老學校的替代品:

var that = this; // capture the correct this in a variable 
firebase.database().ref('/users/' + userId).on('value', function(snapshot) { 
    that.authState.prenom = snapshot.val().prenom; 
    that.authState.nom = snapshot.val().nom; 
}); 

或者:

firebase.database().ref('/users/' + userId).on('value', function(snapshot) { 
    this.authState.prenom = snapshot.val().prenom; 
    this.authState.nom = snapshot.val().nom; 
}, this); // pass in the this as the last parameter 

欲瞭解更多信息,我強烈建議閱讀How to access the correct `this` inside a callback?

+0

非常感謝!胖箭頭功能對我來說是完美的:) –