可观察类的两个数组之间的映射 [英] Mapping between two arrays of observable classes

查看:67
本文介绍了可观察类的两个数组之间的映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个给定的类 SgFormsBase QuestionBase ,其成员名称略有不同,我想将其中一个的 observable [] 转换为其他.

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)

推荐答案

由于可观察的源是 SgFormsBase [] 的可观察对象,因此它发出的每个值都是一个完整的数组.因此,可观察的 map 运算符将接收整个数组.您需要在可观察的 map 运算符内添加另一个数组映射运算符.

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

这篇关于可观察类的两个数组之间的映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆