@angular/fire 和 RxJS:Return 来自 rxjs 的值 pipe/map

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

我想要此函数 return id 的值,但我不知道在哪里给出 return 语句。

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();
}

现在您的内部 map 函数(对 actions 数组进行操作的函数)没有 return 任何东西。

如果你想 return 一个包含 actions 数组中所有 id 的数组,你可以简单地这样做

...
map(actions => actions.map(a => a.payload.doc.id))
...

首先,您必须 return id 从您分配给 id 变量的映射中,然后您需要 return 此函数结果为 observable 所以您可以订阅您的组件并在那里获得 return。

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

希望这对您有所帮助!