【问题标题】:Convert an Observable<Type1> to an Observable<Type2>将 Observable<Type 1> 转换为 Observable<Type 2>
【发布时间】:2020-12-27 00:51:16
【问题描述】:

假设我定义了 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 并创建一个新的 observable SpecFormatB 并从我的方法中返回它。 有什么简单的方法吗?

我的转换逻辑是这样的:

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

【问题讨论】:

  • 您可以格式化从可观察对象返回的值,而不是可观察对象本身

标签: angular typescript rxjs rxjs-observables


【解决方案1】:

你可以使用来自RxJs的管道ma​​p

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-28
      • 2021-05-24
      • 1970-01-01
      • 2016-08-15
      • 1970-01-01
      • 2015-09-24
      • 2019-07-27
      相关资源
      最近更新 更多