Get the current user logged in Angular - Firebase

懵懂的女人 提交于 2020-01-06 08:00:54

问题


I need to get the user id logged into my web application, this is my auth service.ts:

export class AuthService {
  private authState: Observable<firebase.User>;
  public currentUser: firebase.User = null;

  constructor(
   public afAuth: AngularFireAuth,
   public firestore: AngularFirestore,
   private router: Router) {
    this.authState = this.afAuth.authState;

    this.authState.subscribe(user => {
      if (user) {
        this.currentUser = user;
        console.log('AUTHSTATE USER', user.uid); //this works
        this.router.navigate(['dashboard']);
      } else {
        console.log('AUTHSTATE USER EMPTY', user);
        this.currentUser = null;
      }
    },
    err => {
      console.log('Please try again')
    });
 }
... //STUFF
}

whit this code I can log into the console the user id, but what I really need is to use that user id to get the associated document.

this is my main component.ts

export class MainComponent {


  userId: string = '';
  private authState: Observable<firebase.User>;
  public currentUser: firebase.User = null;

  constructor(
      public authService: AuthService,
      public firestore: AngularFirestore,
      private router: Router) {
  }


  ngOnInit() {
    console.log(this.authService.currentUser) //this log 'null'
  }
  ...//STUFF

}

when I log the this.authService.currentUser into the console I get the nullresult. I'd like to store that user.uid from the auth service into the userId varible into the main component.

I guess that the problem is that the main component is loaded before the auth service so I can't get the user ID

Can you guys tell me the trick? Thankyou

来源:https://stackoverflow.com/questions/54961071/get-the-current-user-logged-in-angular-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!