如何在 Angular 7 中忽略序列化为 JSON 的属性

Fab*_*nus 0 json angular

我在分层模型结构中有一个导航属性,在序列化过程中会导致 angular 7 中的循环依赖错误。

export class MyClass {
   // this property should be ignored for JSON serialization
   parent: MyClass;

   childList: MyClass[];
}
Run Code Online (Sandbox Code Playgroud)

我想知道是否有任何内置解决方案(例如,Jackson 存在这样的装饰器:@JsonBackReference)来忽略序列化时的父属性(例如在 http.put 期间)。

非常感谢您的任何建议!

And*_*rei 6

如果你更喜欢用装饰器来处理这个问题,你可以像这样制作自己的

function enumerable(value: boolean) {
    return function (target: any, propertyKey: string) {
        let descriptor = Object.getOwnPropertyDescriptor(target, propertyKey) || {};
        if (descriptor.enumerable != value) {
            descriptor.enumerable = value;
            Object.defineProperty(target, propertyKey, descriptor)
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

然后像这样将属性标记为不可枚举

class MyClass {
   @enumerable(false)
   parent: MyClass;
}
Run Code Online (Sandbox Code Playgroud)

另一个选择是重新定义 toJSON 行为

MyClass {
...
public toJSON() {
 const {parent, ...otherProps} = this;
 return otherProps;
}
Run Code Online (Sandbox Code Playgroud)