【问题标题】:Clone instance with getter/setter field decorations使用 getter/setter 字段装饰克隆实例
【发布时间】:2021-01-14 10:03:40
【问题描述】:

我有一个这样填充的类(来自 json):

export class blogEntry {

  hasImage: boolean;
  @newItem(Video) video: Video;
  @newItem(Author) author: Author;
  @newItem(Comments) comments: Comments;
  @newItem(Picture) blogImage: Picture;
  @newItem(PictureCaption) pictureCaption: PictureCaption;
  @newItem(TextSummary) summary: TextSummary;

  constructor(data: blogEntry|Object) {
    Object.assign(this, data);
  }

}

装饰器是这样定义的(在单独的文件中):

export function newItem<T extends EditablePart>(type) {
  return function(target: Object, propertyKey) {
    let value: T;
    Object.defineProperty(target, propertyKey, {
      get: function(): T {
        return value;
      },
      set: function(newVal: T) {
        if (newVal) {
          value = construct(type, newVal);
        }
      },
      enumerable: true
    });
  }
}

export function construct<T extends EditablePart>(type: { new(...args : any[]): T ;}, newVal) {
  return new type(newVal);
}

所有带注释的类型都扩展了 EditablePart。

使用此类更改数据后(通过使用带注释的字段,即通过那里提供的 getter/setter),我想将类数据作为 json 保存到我的后端服务器。在介绍类中的装饰器之前,我可以使用:

publish(): blogEntry {
   return new blogEntry(this);
}

现在我只得到 hasImage。在 chrome 中使用开发人员工具时,我可以看到这些字段,但我必须单击它们后面的点('invoke property getter')才能检索数据。

有没有想过如何克隆这个类(我想继续使用这个类)?任何帮助将不胜感激!

【问题讨论】:

    标签: json angular typescript clone decorator


    【解决方案1】:

    我突然想到使用 JSON.stringify(...) 和一个自定义函数来帮助您解析指令。

    根据 stringify 文档,该函数将是一个替换函数。

    示例:我有一个想要保存在 BD 中的组件。我的组件有一个 ViewChild 装饰器,我也想保存它。我知道我的 ViewChild 是一个 ElementRef,但我不想保存这样的结构:

    {
      nativeElement: {}
    }
    

    以上是我的 JSON.stringify(...) 函数获取我的 ViewChild 属性时的结果,因此我的替换函数开始起作用。

    JSON.stringify(this, function(key, value) {
          const isViewChild = value.nativeElement; // This is for identifying a ViewChild.
          if (isViewChild) {
            return isViewChild.innerHTML; // I want to resolve it with HTML only.
          }
          return value;
     });
    

    现在,我的 viewchild 如下所示:

    {
      ...other properties,
      myViewChild: '<div>My viewchild translated to html</div>'
    }
    

    其他方法是覆盖 toJSON 函数。再次使用我的组件:

    @Component({...})
    export class MyComponent {
      @ViewChild('mySon') myViewChild: ElementRef<any>;
      ...other properties
    
      toJSON() {
        return { myViewChild: this.myViewChild.nativeElement.innerHTML, ...otherProps };
      }
    }
    

    当您对组件进行 JSON.stringify 时,您将使用已解析的指令来获取组件。

    试试吧!

    【讨论】:

      猜你喜欢
      • 2017-11-28
      • 1970-01-01
      • 1970-01-01
      • 2016-04-01
      • 2021-11-04
      • 1970-01-01
      • 2018-06-30
      • 2011-01-12
      • 2017-04-10
      相关资源
      最近更新 更多