首页 > 解决方案 > 如何在Angular 7中忽略序列化为JSON的属性

问题描述

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

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

   childList: MyClass[];
}

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

非常感谢您的任何建议!

标签: jsonangular

解决方案


如果你喜欢用装饰器来处理这个,你可以自己做一个这样的

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

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

class MyClass {
   @enumerable(false)
   parent: MyClass;
}

其他选项是重新定义 toJSON 行为

MyClass {
...
public toJSON() {
 const {parent, ...otherProps} = this;
 return otherProps;
}

推荐阅读