@ angular / fire和RxJS:从rxjs pipe / map返回值

问题描述 投票:1回答:2

我希望这个函数返回id的值,但我无法弄清楚返回语句的位置。

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();
}
angular ionic-framework rxjs angularfire2 angularfire
2个回答
1
投票

首先,您必须从已分配给id变量的地图返回id,然后您需要将此函数结果作为observable返回,以便您可以在组件中订阅并返回那里。

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
   }     
}

希望这会有所帮助!


1
投票

现在你的内部map函数(在actions数组上运行的函数)不会返回任何内容。

如果你试图从id数组返回一个包含所有actionss的数组,你可以这样做

...
map(actions => actions.map(a => a.payload.doc.id))
...
© www.soinside.com 2019 - 2024. All rights reserved.