I have method in my service, inside which I am trying to return an Observable of the User object. Here is the my code -
constructor(private firestore: AngularFirestore,
private db: AngularFireDatabase) { }
/**
* get user with given email, if not return null
*
* @param email email to fetch
*/
getUserByEmail(email: string): Observable<User> {
var user: User;
let userRef = this.firestore.collection("users").ref.where('email', '==', email);
userRef.get().then(res => res.forEach(userDoc => {
user = userDoc[0].data() as User; // since email IDs are unique, I want the 0th element.
user.id = userDoc[0].id;
console.log(user); // has the data
// return user; // doesn't work, not the right thing
}));
console.log(user); // undefined, since call is async
return of(user);
}
Inside the component, I want that data for the next steps, so I did this -
checkEmail() {
var user$: User
this.us.getUserByEmail(this.existingUserForm.value.email).subscribe(user => {
console.log(user);
if (user) {
this.msg$ = "success";
// next steps
}
else {
this.msg$ = "User with this email does not exist!";
}
});
}
I am not sure how to return an observable from my service, so that I can use the data in my component. And is this the right way to do what I am trying to?