Aritra Sur Roy
Aritra Sur Roy

Reputation: 322

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

Upvotes: 0

Views: 214

Answers (2)

Gorynych
Gorynych

Reputation: 100

The best way to do that is to use a separate adapter 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
    );
  }
}

Once adapter is injected in the component.

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

Upvotes: 0

Derviş Kayımbaşıoğlu
Derviş Kayımbaşıoğlu

Reputation: 30545

you can use pipe map from RxJs

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

Upvotes: 1

Related Questions