I developed an application using Angular 7 with Firestore for crud operations. Everything is functioning well with a single user. However, I am now looking to expand it and link data to each individual logged-in user. Unfortunately, I am struggling to find detailed resources online.
Currently, I have users stored in a collection. My goal is to set up a 'vacations' collection nested under each user, specifically for their vacation details. I believe the initial step involves retrieving the unique id of the currently logged-in user and then updating the necessary functions to modify the collection by using `.doc('current user id')`.
Below is the code snippet I utilized to fetch the current user's uid:
this.userID = this.firestore.collection('users').doc(this.auth().user.uid);
Errors encountered during pre-compilation:
1- Type 'AngularFirestoreDocument<{}>' is not assignable to type 'string'
2- Cannot invoke an expression whose type lacks a call signature. Type 'AuthService' has no compatible call signatures.
This is how the data organization looks currently:
https://i.sstatic.net/e1V51.png
The authentication service code snippet is provided below:
export class AuthService {
user$: Observable<User>;
constructor(
public afAuth: AngularFireAuth,
public afs: AngularFirestore,
public router: Router
) {
// Fetch the auth state and retrieve the Firestore user document or return null
this.user$ = this.afAuth.authState.pipe(
switchMap(user => {
// User is logged in
if (user) {
return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
} else {
// User is logged out
return of(null);
}
})
)
}
googleLogin() {
const provider = new auth.GoogleAuthProvider()
return this.oAuthLogin(provider);
}
public oAuthLogin(provider) {
return this.afAuth.auth.signInWithPopup(provider)
.then((credential) => {
this.updateUserData(credential.user)
})
}
public updateUserData(user) {
// Store user data in firestore upon login
const userRef: AngularFirestoreDocument<User> = this.afs.doc(`users/${user.uid}`);
const data = {
uid: user.uid,
email: user.email,
displayName: user.displayName,
photoURL: user.photoURL
}
return userRef.set(data, { merge: true })
}
}
Your assistance is greatly appreciated.