Search code examples
angulartypescriptrxjsrxjs-observables

Convert an Observable<Type1> to an Observable<Type2>


Suppose I have 2 interfaces defined like:

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

I call a method and get observable of SpecFormatA. I want to format the observable received and create a new observable of SpecFormatB and return it from my method instead. Is there an easy way to do it?

My conversion logic is like:

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

Solution

  • you can use pipe map from RxJs

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