I want to pass the return value to my component. I wrote this service using firebase. When calling the geLoggedInUser method in my component it returns undefined. Ideally, I want to pass the doc.id to my component from my service please help;
SERVICE
docId: any;
getLoggedInUser() {
this.fireAuth.onAuthStateChanged((user) => {
if (user) {
console.log(user.email, 'user is valid');
const db = collection(this.firestore, 'users');
getDocs(db).then((resp) => {
this.data = [
...resp.docs.map((item) => {
return { ...item.data(), id: item.id };
}),
];
//filter users array to get current logged in users data
this.authUser = this.data.filter((item: any) => {
this.docId = user.uid;
return item.email === user.email;
});
});
} else {
this.router.navigate(['/login']);
return;
}
});
return this.docId;
}
COMPONENT
ngOnInit(): void {
console.log(this.auth.getLoggedInUser());
}
2
Answers
I recommend get involved in the Promise and Observable concepts.
https://firebase.google.com/docs/reference/js/v8/firebase.auth.Auth
Your problem is when you call getLoggedInUser() is doings this:
What you can do is use an observable variable in the SERVICE and connect to it from the component.
Please read the following Firebase: Should Promise or Observable be used in an Angular project?
I hope this helps!
In angular, when you use services it’s not common to use variable to pass data to components. To that you should use a observables or promises/await/async.
In this case, I would recommend you use a observable. Here you have an example how you can implement it: