【问题标题】:Mapping between two arrays of observable classes两个可观察类数组之间的映射
【发布时间】:2019-04-05 15:34:33
【问题描述】:

我有两个给定的类 SgFormsBase 和 QuestionBase,其成员名称略有不同,我想将其中的 observable[] 翻译成另一个。

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)

【问题讨论】:

    标签: angular dictionary rxjs observable


    【解决方案1】:

    由于源 observable 是 SgFormsBase[] 的 observable,它发出的每个值都是一个完整的数组。因此,可观察的map 运算符接收整个数组。您需要在可观察的 map 运算符中使用另一个数组映射运算符。

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

    【讨论】:

      【解决方案2】:

      参数sgForms用SgFormsBase的数组解析。因此,您需要做的是分别发出每个值,将各个值映射到 QuestionBase 实例,然后将其压缩回一个数组。

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

      【讨论】:

      • @cristian.t 的版本有效,你的看起来很有趣。太糟糕了,由于Argument of type 'OperatorFunction&lt;SgFormsBase, QuestionBase&gt;' is not assignable to parameter of type 'OperatorFunction&lt;T, QuestionBase&gt;'. Type 'SgFormsBase' is not assignable to type 'T'.,它无法编译
      • 有趣。最近,我的反应流编译遇到了一些间歇性问题。尽管如此,它们仍按预期工作。我在我的一个项目中发布了这段代码,它没有显示任何编译错误。这是我的版本:RxJS:版本 6.4.0 本地打字稿:版本 3.4.1 全局打字稿:版本 3.1.1
      • 我的版本相同。 compilerOptions: strict: true, module es2015
      • 相同。您的构建器是否允许您运行代码?我不明白为什么不能将 SgFormsBase 类型转换为泛型类 T。
      • 是的,这是运行时错误,而不是编译错误。我只是从头开始重建我的完整 node_module,结果相同。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 2017-06-20
      • 2018-07-25
      • 2019-02-25
      • 1970-01-01
      • 2012-02-20
      • 2012-10-14
      相关资源
      最近更新 更多