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

Convert an Observable<Type1> to an 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 的可观察性。我想格式化收到的 observable 并从我的方法创建一个新的 SpecFormatB 和 return observable。 有简单的方法吗?

我的转换逻辑是这样的:

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

您可以使用来自 RxJs

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

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

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