问题
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 null
result.
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