将Observable <Type1>转换为Observable <Type2>

问题描述

假设我有2个定义如下的接口:

export interface SpecFormatA{
  cpuFullname: string;
  cpumanufacturer: string;
  Physicalmemory: number;
  Pagesize: number;
  OSinfo: string;
  Videocontroller: Array<string>
}

export interface SpecFormatB{
  cpuname: string;
  OSinfo: string;
  RAM: string;
  VideoController: Array<string>;
}

调用一个方法,并观察到SpecFormatA。我想格式化接收到的可观察对象的格式,并创建SpecFormatB的新可观察对象,然后从我的方法中返回它。 有简单的方法吗?

我的转换逻辑就像:

SpecFormatB.cpuname = SpecFormatA.cpuFullname
SpecFormatB.OSinfo = SpecFormatA.OSinfo
SpecFormatB.RAM = `${SpecFormatA.Physicalmemory / Math.pow(1024,3)} GB`
SpecFormatB.VideoController =  SpecFormatA.VideoController

解决方法

您可以使用RxJs

中的管道地图
myObservable.pipe(map(ev => <SpecFormatB>{
    CPUname: ev.CPUFullname
    ....
}));
,

最好的方法是使用单独的适配器类

export interface Adapter<SpecFormatA,SpecFormatB> {
  adapt(entity: SpecFormatA): SpecFormatB;
}
export class SpecFormatBModel implements SpecFormatB {
  constructor(
    public readonly CPUname: string,public readonly OSinfo: string,public readonly RAM: string,public readonly VideoController: Array<string>
  ) {}
}

@Injectable({
  providedIn: 'root',})
export class SpecFormatAdapter implements Adapter<SpecFormatA,SpecFormatB> {
  adapt(specFormatA: SpecFormatA): SpecFormatB {
    return new SpecFormatBModel(
      SpecFormatB.CPUFullname,SpecFormatB.OSinfo,SpecFormatB.Physicalmemory,SpecFormatB.Videocontroller
    );
  }
}

将适配器插入组件中。

myObservable.pipe(map(ev => this.specFormatAdapter.adapt(SpecFormatA)));