我试图从Firebase谷歌登录获取当前用户信息,但我真的很困惑为什么angularfire不会让我存储当前的用户信息。当我尝试输出this.user
的值但在块外返回null
值时,将返回当前用户信息。需要一些帮助来解决这个问题。
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';
import { FirebaseService } from '../../services/firebase.service';
import * as firebase from 'firebase';
import { AngularFire, FirebaseAuthState } from 'angularfire2';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
public user: FirebaseAuthState;
public userProfiles: any;
public displayName: string;
constructor(
public af:AngularFire,
public flashMessage:FlashMessagesService,
private firebaseService: FirebaseService,
private router:Router
) {
this.af.auth.subscribe(user => {
if(user) {
// user logged in
this.user = user;
console.log('if');
console.log(this.user);
}
else {
// user not logged in
// this.user = ;
console.log('else');
}
})
console.log(this.user);
}
ngOnInit() {
this.af.auth.subscribe((state: FirebaseAuthState) => {
this.userProfiles = state;
this.displayName = this.userProfiles.auth.displayName;
// console.log(this.userProfiles);
});
console.log(this.firebaseService.getCurrentUser());
}
login(){
this.af.auth.login();
}
logout(){
this.af.auth.logout();
this.flashMessage.show('You are logged out',
{cssClass: 'alert-success', timeout: 3000});
}
username(){
}
}
答案 0 :(得分:0)
当我尝试输出this.user的值但返回块外的空值时,返回当前用户信息。需要一些帮助来解决这个问题。
放大您的代码
this.af.auth.subscribe(user => {
if(user) {
// user logged in
this.user = user;
console.log('if');
console.log(this.user);
}
else {
// user not logged in
// this.user = ;
console.log('else');
}
})
console.log(this.user);
呼叫this.af.auth.subscribe(
是异步的,对同步代码没有影响。这基本上类似于
this.user = null;
setTimeout(() => {
this.user = 'something'
});
console.log(this.user); // null!
在订阅栏内使用用户。如果您想对非空用户执行操作,请随意从订阅内部调用函数。