基于 ClassName 创建类的实例:字符串 [英] Creating Instance Of Class Based On ClassName : string
问题描述
在任何人将其标记为重复之前,请阅读以下内容,
Before anyone marks this as duplicate please read below,
我的场景不仅涉及 TypeScript,还涉及 Angular2.
My scenario doesn't just involve TypeScript but also Angular2.
目标
我需要 app.component.ts 中的一个方法,它接受一个字符串(类名)并创建它的一个实例.这些类存在于其他 ts 文件中.
I need a method in app.component.ts which takes a string(Class Name) and creates a instance of that. The classes exist in other ts files.
现在是用例:我有一个方法 getWidgetObjectFromClassName(className : string) : Object{}
需要返回字符串格式的类名的实例.问题来了,
Now to the use case:
I have a method getWidgetObjectFromClassName(className : string) : Object{}
which needs to return the instances of the class name which is in string format.
Now the problem,
我尝试使用 NameSpace 并执行 let instance = new SampleNS['OtherName']();
(SampleNS 是一个命名空间),在单个文件的情况下工作得很好.
I tried using NameSpace and doing let instance = new SampleNS['OtherName']();
(SampleNS is a namespace), works perfectly fine in the case of single file.
但现在我有多个 ts 文件可以说 interfaces.ts、classes.ts、otherclasses.ts.我在 interface.ts 中使用 export namespace SampleNS{}
一切正常,接下来在 classes.ts 中使用 ///<reference path="interfaces.ts"/>
和相同的命名空间 SampleNS
.
But Now
i have multiple ts files lets say interfaces.ts, classes.ts, otherclasses.ts. Im using export namespace SampleNS{}
in interface.ts all works, next in classes.ts using the /// <reference path="interfaces.ts" />
and same namespace SampleNS
.
现在我的方法 getWidgetObjectFromClassName(className : string) : Object{}
在 xyz.ts 中,现在我应该提供哪个导入?,我的意思是如果我说`import {SampleNS} from'./接口'.这里的问题是我只能导入单个文件的命名空间(即使它是相同的),因此我创建的实例仅限于导入该特定文件的命名空间.
Now my method getWidgetObjectFromClassName(className : string) : Object{}
is in xyz.ts, and now which import should i give?, my point being if i say `import {SampleNS} from './interfaces'.
The problem here is i can only import a single file's namespace(even though its the same) hence im creating instance is limited to the import of that specific file namespace.
Plunker 链接 https://plnkr.co/edit/pt90F34KPsGoHDpSUQFD?p=预览
推荐答案
Use as
with import like
Use as
with imports like
import * as widgets from './lib';
...
this.widgetInstance = new widgets[className]();
我从另一个答案中记住了这一点,但我找不到它的功劳:-/
I remember this from another answer but I couldn't find it to give some credit :-/
这篇关于基于 ClassName 创建类的实例:字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!