Mapping between two arrays of observable classes

回眸只為那壹抹淺笑 提交于 2021-01-29 12:54:46

问题


I have two given classes SgFormsBaseand QuestionBase with slightly different member names, and I want to translate observable[] of one to the other.

import { of, Observable } from 'rxjs'
import { map} from 'rxjs/operators'

class SgFormsBase{
  constructor(
     public id: number,
     public survey: string
  ){}
}

class QuestionBase{
  constructor(
     public qid: number,
     public qsurvey: string
  ){}
}

const a = new SgFormsBase(11, 'Endo')
const b = new SgFormsBase(12, 'Kolo')
const sg = of([a, b] )

function toQuestionsBase(sgforms: Observable<SgFormsBase[]>): Observable<QuestionBase[]> {
  return sgforms.pipe(map(
     sgform =>  new QuestionBase(sgform.id, sgform.survey)))
}

toQuestionsBase(sg)

回答1:


Since the source observable is an observable of SgFormsBase[], each value it emits is a whole array. The observable map operator therefore receives the entire array. You need another array map operator inside the observable map operator.

function toQuestionsBase(sgforms: Observable<SgFormsBase[]>): Observable<QuestionBase[]> {
  return sgforms.pipe(map(
    sgforms => sgforms.map(sgform => new QuestionBase(sgform.id, sgform.survey))))
}



回答2:


the parameter sgForms resolves with an array of SgFormsBase. So, what you'll need to do is emit each value individually, map the individual values to QuestionBase instances and then zip it back up into an array.

function toQuestionsBase(sgforms: Observable<SgFormsBase[]>): Observable<QuestionBase[]> {
  return sgforms.pipe(
    mergeMap((sgs: SgFormsBase[]) => sgs),
    map((sgForm: SgFormsBase) => new QuestionBase(sgForm.id, sgForm.survey)), 
    toArray());
}


来源:https://stackoverflow.com/questions/55538941/mapping-between-two-arrays-of-observable-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!