序列化角度组件 [英] Serialize Angular Component

查看:60
本文介绍了序列化角度组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要序列化角度组件的引用(不是实例).例如,如果我具有以下组件:

I need to serialize the reference (not an instance) of an angular component. For example, if I have the following Component:

@Component({
  selector: 'component-selector',
  template: ...
})
export class CustomComponent {

我需要像这样保存对它的引用:

I need to save a reference to it like this:

class CustomClass {
  component: Type<CustomComponent> = CustomComponent;

  ...
}

在这一点上,一切都按预期工作,我可以根据需要使用该组件.现在的问题是,我需要序列化CustomClass并将其保存到文件中.

At this point, everything works as expected, and I can use the component as I need. The problem now is that I need to serialize the CustomClass and save it to a file.

当我尝试执行JSON.stringify(customClass)时,字段component消失了,如果我尝试使用JSON.parse解析字符串,则会导致使用undefined componentcustomClass实例.

When I try to do JSON.stringify(customClass), the field component is disappearing and if I try to parse the string with JSON.parse, results in a customClass instance with undefined component.

我找到了此要点,以便对函数进行序列化和反序列化,但是它没有不能为我工作(我想虽然Type界面是从Function扩展的,但不一样,不是吗?)

I found this gist in order to serialize and deserialize a function, but it didn't work for me (I guess although Type interface extends from Function, is not the same, isn't it?)

如何序列化Angular组件?

How can I serialize the Angular Component?

推荐答案

我找到了一种解决方法(为此找到的唯一解决方案),并且正在创建从字符串(标识符)到组件的映射.例如,在代码的某些部分中,我们有如下内容:

I found a workaround (the only solution I found for this) and is creating a mapping from a string (identifier) to the component. For example, in some part of the code we have something like this:

let mapping = [
  {name: 'component1', component: Component1},
  {name: 'component1', component: Component1},
  ...
]

因此,在对对象进行字符串化时,可以保存用于标识组件的字符串,然后在将其再次转换为对象时,可以在映射中查找组件引用.效果很好!

So, when the object is stringified, you can save the string that identifies the component, and when you convert it into an object again, you look in the map for the component reference. It works perfectly!

这篇关于序列化角度组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆