我尝试将类型字符串化,将其保存到localStorage并再次解析它以在Angular中创建动态组件。代码是:
// panelTypes is a map of type: [ SomeComponent, AnotherComponent, ...]
private panelTypes: Type<DockablePanel>[];
// Stringifying
const saveString = JSON.stringify(this.dockTree, (key, value) => {
if (key === 'type') {
const panel: Type<DockablePanel> = this.panelTypes.find((panelType: Type<DockablePanel>) => {
return panelType.name === value;
});
if (!panel) {
console.log('Couldn\'t find paneltype ' + value);
} else {
return panel;
}
} else {
return value;
}
});
// Parsing
const stored = JSON.parse(storageItem, (key, value) => {
if (key === 'type') {
return value.name;
} else {
return value;
}
});
这在开发中运行时起作用,但在生产中代码被混淆/缩小,导致每个value.name都像是&#39; e&#39;或者&#39; n&#39;。
有没有办法在TypeScript中进行字符串化并稍后解析类型? JavaScript类可以用来识别类型吗?
如果没有,是否有办法防止某些值被混淆/缩小?
[编辑]
我尝试使用Angular的ComponentFactoryResolver存储/恢复动态布局,如下所示:
constructor(private componentFactoryResolver: ComponentFactoryResolver,
private dockerService: DockerService,
private application: ApplicationRef,
private changeDetector: ChangeDetectorRef) {
}
ngOnInit(): void {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.panel.type);
this.panelRef = this.dynamicInsert.createComponent(componentFactory);
}
DockTree是一个由两种DockNode组成的树:DockContainers和DockPanels:
export class DockTreeNode {
parent: DockTreeContainer;
}
export class DockTreeContainer extends DockTreeNode {
private orientation: Orientation;
private left: DockTreeNode;
private right: DockTreeNode;
}
export class DockTreePanel extends DockTreeNode {
type: Type<DockablePanel>;
args: DockArguments;
movable: boolean;
ref?: ViewRef;
}
所以我的树看起来像这样:
每个面板节点都有一个应该包含Type的类型字段。此类型需要保存到localStorage,然后从中恢复。 Minifiying虽然让我在Object.name中缩短了无意义的类名,所以我无法使用它。