我想制作像Linkedin博客这样的网站。
我可以像这样创建动态组件。但是当我重新加载浏览器时,动态创建的组件就消失了。
如何将动态创建的组件缓存到 localStorage?以及当我重新加载浏览器时如何从 localStorage 动态加载组件?
还有一个问题。我需要在这段代码中使用 ngOnDestroy() 吗?
我像这样添加了 localStorage 部分。但是发生“在 JSON.stringify 将循环结构转换为 JSON”类型错误。
缓存 ComponentRef 对象数组的最佳解决方案是什么?
⬇︎这是父组件
// I added this part
import { COMPONENTS_REFERENCES } from '../../constants';
export class ParentComponent implements OnInit {
index: number;
componentsReferences = [];
@ViewChild('viewContainerRef', { read: ViewContainerRef }) VCR: ViewContainerRef;
constructor(
private CFR: ComponentFactoryResolver) {
}
ngOnInit() {
// I added this part.
const cachedComponents = JSON.parse(localStorage.getItem(COMPONENTS_REFERENCES));
if (cachedComponents && cachedComponents.length > 0) {
this.componentsReferences = cachedComponents;
}
this.index = 1;
}
addChild() {
const componentFactory = this.CFR.resolveComponentFactory(ChildComponent);
const componentRef: ComponentRef<ChildComponent> = this.VCR.createComponent(componentFactory);
const currentComponent = componentRef.instance;
currentComponent.selfRef = currentComponent;
currentComponent.index = this.index++;
currentComponent.userId = this.user.id;
currentComponent.compInteraction = this;
this.componentsReferences.push(componentRef);
// I added this part
localStorage.setItem(COMPONENTS_REFERENCES, JSON.stringify(this.componentsReferences));
}
removeChild(index: number) {
if (this.VCR.length < 1) {
return;
}
const componentRef = this.componentsReferences.filter(x => x.instance.index === index)[0];
const component: ChildComponent = <ChildComponent>componentRef.instance;
const vcrIndex: number = this.VCR.indexOf(componentRef);
this.VCR.remove(vcrIndex);
this.componentsReferences = this.componentsReferences.filter(x => x.instance.index !== index);
// I added this part
localStorage.setItem(COMPONENTS_REFERENCES, JSON.stringify(this.componentsReferences));
}
// ... and another ChildComponent add/remove method here
}
⬇︎这是父组件的HTML
<div>
<ng-template #viewContainerRef></ng-template>
</div>