1
我試圖從Firebase數據庫中獲取項目,但看起來不行。 操作員「這個」不是快照功能工作(上線this.authState.prenom = snapshot.val().prenom
)Angular 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);
}
}
非常感謝!胖箭頭功能對我來說是完美的:) –