Search code examples
angularionic-frameworkangularfire

How do I access a sub-collection and return it as an Observable?


I am able to access the sub-collection if I add the collectionRef manually. I have tried to use the CollectionReference outside of the constructor but I get errors saying Property 'collectionRef' does not exist on type 'UnitlogService'. The only way I see around this some how getTasks before the constructor or find away to use CollectionReference outside of the constructor. any help or AngularFire references docs on sub-collections would be greatly helpful.

service file ts

import { collection, CollectionReference, Firestore }from'@angular/fire/firestore';

export class UnitlogService {
  private collectionRef: CollectionReference;

  constructor( private firestore: Firestore, private auth: Auth, private storage: Storage ) {

    // const id inserted manually
    // would like to use id form getTasks(id) which connects the page with this service
    const id = 'LvuYX0jreCB1sL5IORCM'

     this.collectionRef = collection(this.firestore, `tasks/${id}/unit-logs-sub-collection`);
     onAuthStateChanged(this.auth, (user) => {
       if (user) {
         const tasksQuery = query( this.collectionRef);
         const collectionSub = collectionData(tasksQuery, {
           idField: 'id',
        }) as Observable<Task[]>;
          this.tasksSub = collectionSub.subscribe((tasks) => {
          this.tasks.next(tasks);
        });
      } else {
      this.tasks.next([]);
      this.tasks.unsubscribe();
    }
  });
}

getTasks(id: any) {
  console.log("id",id)
  return this.tasks.asObservable() 
} 

Solution

  • Turns out a constructor not really modifiable if you are user AngularFire. As a workaround I skipped CollectionReference and used the following code outside of the constructor to query the sub collection and return it as an Observable to use on other pages

    ts service

    import { collection, CollectionReference, Firestore }from'@angular/fire/firestore';
    
    getSubCollection(id: any) {
      // id of collection "task" is passed form the page using the service
      const col = collection(this.firestore, `tasks/${id}/unit-logs-sub-collection`);
      // const col is the link to the sub collection
      const tasksQuery = query( col );
      const collectionSub = collectionData(tasksQuery, { idField: 'id',}) as Observable<Task[]>;
      
      this.tasksSub = collectionSub.subscribe((tasks) => { this.tasks.next(tasks); console.log("this.tasks",this.tasks);});
      // this.tasksSub is a BehaviorSubject
      return this.tasks.asObservable();
      // returns a Observable {source: BehaviorSubject}
    }