Search code examples
angularforeachobservableangularfire

Observable won't exit foreach?


This has got to be my head-space error in learning Firebase. All I want to do is to is get a document if it exists, based on a value it contains when I do not have the document id:

myCollection/[some id]/myField:myValue

I'm trying to use ValueChanges to iterate through the observable and see if a document exists based on the where clause. I do get the document I'm looking for, but I effectively cannot use it because when I iterate through the array in the observable, it seems to never return. I can log the item to the console, but never get to result after the loop:

      var colRef: AngularFirestoreCollection<MyType>;
      var obs$: Observable<MyType[]>;

      colRef = this.afs.collection<MyType>('myCollection', ref => {
         return ref.where('myField', '==', 'myValue');
      });

      obs$ = colRef.valueChanges();
      var result = obs$.forEach(x => 
      {
         var item = x[0];
         // get here OK
         console.log(`item = ${JSON.stringify(item)}`)
         return item;
      })

      // never get here
      console.log(`result = ${JSON.stringify(result)}`)

What am I missing? Or the bigger question is, am I even approaching this correctly? Seems like a lot of running around to get a document...

Thanks for the help!


Solution

  • You need to change your code to

      var colRef: AngularFirestoreCollection<MyType>;
      var obs$: Observable<MyType[]>;
    
      colRef = this.afs.collection<MyType>('myCollection', ref => {
         return ref.where('myField', '==', 'myValue');
      });
    
      obs$ = colRef.valueChanges();
      obs$.subscribe((x: MyType[]) => 
      {
         console.log(x);  
      });
    

    Pay attention this is an async operation, you are treating it as a sync operation