我正在尝试映射一个可观察对象,从我返回的可观察对象中获取一个值,然后将该值提供给另一个可观察对象,然后返回该结果。这是我到目前为止的内容:

  getJobsByUser(user: User): Observable<Job[]> {
    return this.getUsersGroupsAsObservable(user.uid, 'contacts').map(groups => {
      groups.map(group => {
        this.getJobsbyGroup(group.id);
      });
    });

  getJobsbyGroup(groupId: string): Observable<Job[]> {
    return this.afs
      .collection<Job>('jobs', ref => ref.where(`group.${groupId}`, '==', true))
      .valueChanges();
  }

  getUsersGroupsAsObservable(
    userId: string,
    type: string = 'users',
  ): Observable<Group[]> {
    return this.afs
      .collection<Group>('groups', ref =>
        ref.where(`${type}.${userId}`, '==', true),
      )
      .valueChanges();
  }

问题是 typescript 表明我的getJobsByUser函数将返回type:void的可观察对象。当我将其输出到模板上时,我什么也没有得到或未定义。我觉得我需要使用switchMap,但对rx/js有点模糊。我不确定如何返回Job []类型的Observable

更新:在@Pranay Rana的帮助下,我现在正在返回数组,并且可以得到如下第一个值:

  getJobsByUser(user: User): Observable<Job[]> {
    return this.getUsersGroupsAsObservable(user.uid, 'contacts').pipe(
      mergeMap(groups => {
        // returns an array of groups - we need to map this
        return this.getJobsbyGroup(groups[0].id); // works with the first value - do we need another map here?
      }),
    );
  }

更新2:我设法从firestore中获取了一些数据,但是它发出了多个可观察对象,而不是组合流:

this.fb.getUsersGroupsAsObservable(user.uid, 'contacts')
   .switchMap(groups => {
      return groups.map(group => this.fb.getJobsbyGroup(group.id));
   })
    .subscribe(res => {
       console.log(res);
       // this emits multiple observables rather than one
       this.job$ = res;
    });

最佳答案

下面的方法在Way to handle Parallel Multiple Requests中进行了详细讨论

下面的方法利用mergemap

getJobsByUser(user: User) {
     return this.getUsersGroupsAsObservable(user.uid, 'contacts').pipe(
       mergeMap(group => this.getJobsbyGroup( group.id))
     );
}

callingfunction(){
  const requests = this.getJobsByUser(this.user);
  requests.subscribe(
  data => console.log(data), //process item or push it to array
  err => console.log(err));
}

您也可以使用forkJoin
getJobsByUser(user: User) {
         return this.getUsersGroupsAsObservable(user.uid, 'contacts').pipe(
           map(group => this.getJobsbyGroup( group.id))
         );
    }

    callingfunction(){
      const requests = forkJoin(this.getJobsByUser(this.user));
      requests.subscribe(
      data => console.log(data), //process item or push it to array
      err => console.log(err));
    }

关于angular - 通过映射另一个Observable返回一个Observable,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50809542/

10-12 07:37
查看更多