Search code examples
angularionic-frameworkrxjsangularfire2angularfire

@angular/fire and RxJS: Return value from rxjs pipe/map


I want this function to return the value of id but I'm not able to figure out where to give the return statement.

findCardId(card) {
  this.afs.collection('cards', ref=>ref.where('title', '==', `${card.title}`)).snapshotChanges().pipe(
   first(),
   map(actions => { actions.map(a => {
    const id = a.payload.doc.id;
   })})
  ).subscribe();
}

Solution

  • First, you have to return id from your map where you have assigned to id variable and then you need to return this function result as observable so that you can subscribe in your component and get return there.

    your.service.ts

    findCardId(card) : Observable<any> {
          return this.afs.collection('cards', ref=>ref.where('title', '==', `${card.title}`)).snapshotChanges().pipe(
           first(),
           map(actions => { 
              return actions.map(a => {
                const id = a.payload.doc.id;
                return id;
           })})
          )
        }
    

    your.component.ts

     constructor(private myService : MyService) { }
      getCardId() {
       this.myService.findCardId(card).subscribe( id => {
           console.log(id)// here is your id
       }     
    }
    

    Hope this will help!