具有getter / setter字段修饰的克隆实例

问题描述

我有一个这样填充的类(来自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中使用开发人员工具时,我可以看到这些字段,但是我必须单击它们后面的点(“调用属性获取器”)以检索数据。

有人想过如何克隆课程(我想继续使用课程)吗?任何帮助将不胜感激!

解决方法

在我看来,它使用JSON.stringify(...)和一个自定义函数来帮助您之前解析指令。

根据字符串化文档,该函数将是替换函数。

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

{
  nativeElement: {}
}

以上是我的JSON.stringify(...)函数获得ViewChild属性后使我的replacer函数起作用的结果。

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

现在,我的视子看起来如下:

{
  ...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时,您将获得解析指令的组件。

尝试一下!