Walid Salhi
Walid Salhi

Reputation: 11

Logged User.ID is undefined when i try to get a collection from Firebase in Angular

I am coding a Notes application with Angular and Firebase and everything is working fine except one thing, is when I want to retrieve the notes based on user ID, indeed I do that in the constructor, at first I get the info from the logged user and then I try to retrieve the notes based on the user id. But each time "user.id" is "undefined", I do not understand why it is undefined, while the variable contains the id retrieved by Angular Firebase.

this is the code of the Note.service.ts constructor:

  notesCollection: AngularFirestoreCollection<Note>;
  notesDocument: AngularFirestoreDocument<Note>;
  userData: string; // Save logged in user data

  constructor(
    private afs: AngularFirestore,
    private auth: AuthService,
    private afAuth: AngularFireAuth
  ) {
    this.afAuth.authState.subscribe((user) => {
      if (user) {
        this.userData = user.uid;
        // we store the name of the collection that we want to work with//
      } else {
        alert('no data for user');
      }
    });
///Here is where i try to retrieve the collection of notes
    this.notesCollection = this.afs.collection('notes', (ref) =>
      ref.where('authorId', '==', this.userData).orderBy('date', 'desc') // this.userData is Undefined
    );
  }

I alredy tried to add

 ref.where('authorId', '==', this.userData || null).orderBy('date', 'desc')

But then the userData will be always null

How can I get the notes collection when the userData has alredy and Id in it?

Thank you :)

Upvotes: 0

Views: 165

Answers (1)

Ahmad Abu Saa
Ahmad Abu Saa

Reputation: 808

you should move retrieving notes collection to inside the callback of getting user data, to make sure you have user data then you load notesCollection, something like this notesCollection: AngularFirestoreCollection; notesDocument: AngularFirestoreDocument; userData: string; // Save logged in user data

  constructor(
    private afs: AngularFirestore,
    private auth: AuthService,
    private afAuth: AngularFireAuth
  ) {
    this.afAuth.authState.subscribe((user) => {
      if (user) {
        this.userData = user.uid;
        this.notesCollection = this.afs.collection('notes', (ref) =>
           ref.where('authorId', '==', this.userData).orderBy('date', 'desc') 
       );
      } else {
        alert('no data for user');
      }
    });


 }

Upvotes: 1

Related Questions