首页 > 解决方案 > 将字符串类型转换为组件

问题描述

我必须在 Angular 项目中创建路由文件,并且所有路径和组件名称都存储在数据库中。

组件将根据登录用户权限进行选择

现在我想在路由模块文件中创建路由数组。

我将根据用户从数据库中获取所有路由路径并制作路由数组。

但我不知道如何将字符串组件名称转换为组件。

如果有人有想法,请帮忙。

标签: angular

解决方案


You can write a function to return each component type based on the string value, something like this:

convertComponent(componentName: string) {
    switch(componentName) {
        case 'SomeComponent':
            return SomeComponent
            break
        case 'SomethingelseComponent':
            return SomethingelseComponent
            break
        // etc
    }
}

Then call it when you are making your routing module:

{ path: 'something/', component: convertComponent(componentNameString) },

You can also use a registry map instead of the switch case, and set the elements in each component you define.


推荐阅读