问题
I have two given classes SgFormsBase
and 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