javascript - Angular/ typescript : How to get a reference to a class from a string at runtime without importing

标签 javascript typescript

我试图弄清楚如何在运行时从字符串获取对 Angular 2+ (Angular 5) 中的类的引用。我尝试了示例on this page 。这个对我不起作用:

console.log((<any>Object).create(window[className])); // undefined

其他人正在使用导入,我试图避免这种情况。

我没有使用命名空间,但不知道 Angular 是否有自己的命名空间。我尝试窥探窗口对象,看看是否能找到任何东西。我找到的只是 getAllAngularRootElements、getAllAngularTestabilities 和 getAngularTestability,但这些似乎不是我想要的。

最佳答案

我曾经有过类似的需求,需要动态渲染组件,并且只有一个对需要注入(inject)到页面中的类的字符串引用(动态仪表板类型的应用程序)。我最终做了以下事情:

  • 创建服务以通过字符串名称保存组件的引用
  • 将服务注入(inject)模块组件并注册该组件
  • 将服务注入(inject)到需要通过字符串名称获取组件的组件中

这大致就是我所拥有的服务(该类负责实际创建动态组件,而不是像下面那样获取引用):

export class DynamicComponentService {
    private dynamicComponentTypes: { [type: string]: Type<BaseInterfaceSectionComponent> } = {};

    registerDynamicComponentTypes(...dynamicComponentTypesToRegister: { component: Type<BaseInterfaceSectionComponent>, name: string }[]) {
        dynamicComponentTypesToRegister.forEach(dynamicComponentType => {
            this.dynamicComponentTypes[dynamicComponentType.name] = dynamicComponentType.component;
        });
    }

    getDynamicComponentType(name: string): Type<BaseInterfaceSectionComponent> {
        return this.dynamicComponentTypes[name];
    }
}

在这样做之前我并不知道,但实际上您可以将依赖项注入(inject)模块的构造函数中。我利用这个功能来使用服务来注册动态组件:

export class BarChartContentModule {
    constructor(dynamicComponentService: DynamicComponentService) {
        const dynamicComponent = { component: BarChartContentComponent, name: 'BarChartContentComponent' };
        dynamicComponentService.registerDynamicComponentTypes(dynamicComponent);
    }
}

不确定这是否是您正在寻找的内容,但我想我会分享。

关于javascript - Angular/ typescript : How to get a reference to a class from a string at runtime without importing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49661825/

相关文章:

typescript - 在 switch 语句中分配 Typescript 类型

javascript - 尝试将json文件直接加载到HTML中并通过javascript读取其内容

javascript - 为什么使用removeEventListner后无法addEventListener?

javascript - 如何为 vue 声明一个 JS mixin?

typescript - 覆盖/扩展第三方组件的模板

javascript - 为什么我得到 undefined variable ?

javascript - 如何检测angularjs中的水平滚动事件?

javascript - 设置按钮的可见性

javascript - 将字符串 1 和 0 映射为 true 或 false

javascript - 如何使用 Typescript 2.4 的 import() 方法动态获取entryComponents