在使用序列化恰好具有Rxjs主题的类时,我收到了循环对象异常错误。如果我在课堂上订阅主题,当我尝试进行字符串化时,我会得到一个循环对象异常。我的样本课......
export class ThingToStringIfy
{
private someProp : string;
private aSubject = new Subject();
constructor() {
this.aSubject.subscribe();
}
}
所以我的问题是我是否以某种方式错误地使用了主题,或者我碰巧发现了一个错误。我目前正计划使用JSON替换器函数或类似circular-json-es6的东西。任何有关变通方法或改进的建议将不胜感激。如果这是一个错误,我想成为一个好公民并实际报告。
谢谢
以下是违规代码的链接: https://stackblitz.com/edit/angular-cpfsuu?embed=1&file=app/hello.component.ts
答案 0 :(得分:2)
一般来说,观察者和私人成员都不应该被序列化。这导致污染序列化对象的属性不应该存在。
一种方法是在JS输出中隐藏(不可枚举)私有TypeScript属性。这可以通过装饰器来实现:
function Private() {
return function (target: any, prop: string, descriptor?: PropertyDescriptor) {
if (descriptor) {
// method
descriptor.enumerable = false;
} else {
// property initializer
let propSymbol = Symbol(prop);
Object.defineProperty(target, prop, {
configurable: true,
enumerable: false,
get() { return this[propSymbol] },
set(value) { this[propSymbol] = value }
});
}
};
}
export class ThingToStringIfy {
@Private() private someProp : string;
@Private() private aSubject = new Subject();
...
}
装饰器会在private
以及其他只有自己的可枚举属性的地方排除JSON.stringify
个属性。
另一种方法是实现JSON.stringify
代替默认例程使用的toJSON
method:
export class ThingToStringIfy {
private someProp : string;
private aSubject = new Subject();
...
toJSON() {
const publicThis = Object.assign({}, this);
// or lodash.omit or any alternative
delete publicThis['someProp'];
delete publicThis['aSubject'];
return publicThis;
}
}