【问题标题】:Angular import * into module declarationAngular 导入 * 到模块声明中
【发布时间】:2019-04-19 04:47:48
【问题描述】:

我有一个文件,其中包含我的所有组件,如下所示:

components.ts

export { ComponentA } from '../some/path/a.component';
export { ComponentB } from '../some/path/b.component';
export { ComponentC } from '../some/path/c.component';
// ... more here

在我的模块文件中,我有这个:

components.module.ts

import { ComponentA } from '../some/path/components';
import { ComponentB } from '../some/path/components';
import { ComponentC } from '../some/path/components';
// ... more here

@NgModule({
    declarations: [ComponentA, ComponentB, ComponentC]
})
export class ComponentsModule { }

有没有办法我可以只做import * as Components from '../some/path/components' 并将其放入declarations 数组中?我有很多组件,列表可能会变得很大。此外,每次我添加一个新组件时,我都必须更新这两个文件,如果我可以将它作为导出添加到 components.ts 文件中并且import * 会处理其中的任何新组件会更好模块。

如果有人知道,将不胜感激。或者我什至应该这样做吗?如果没有,什么是好的做法?

我尝试这样做,但它返回所有组件的构造函数列表,当我尝试构建它时,Angular 抱怨它无法确定每个组件的模块。

import * as exports from '../some/path/components';
const Components: any[] = Object.keys(exports).map(key => exports[key]);

...
delcarations: [Components]
...

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    尝试将数组传播到声明中:

    declarations: [...Components]
    

    (而不是 Object.keys 然后映射,你也可以简单地使用 Object.values)

    【讨论】:

    • 感谢您让我知道Object.values!真的很有用。我尝试了扩展运算符,我得到了这个错误“错误:模块'ComponentsModule”声明的意外值'null'。我尝试了我的方式和Object.values。我查看了数组,它似乎没有空值。你有什么想法吗?
    • components.ts 中的// ... more here 部分是什么?只是更多的组件出口,还是更多?
    • 我的组件的更多出口。没有别的了。
    • 好的,您是否确实尝试使用Components,例如:declarations: Components
    • 是的,我做到了。当我这样做并尝试构建它时,Angular 抱怨它无法确定每个组件的模块。
    猜你喜欢
    • 2021-11-04
    • 1970-01-01
    • 2020-08-27
    • 2018-10-20
    • 1970-01-01
    • 2018-06-25
    • 1970-01-01
    • 2017-09-25
    • 2013-04-12
    相关资源
    最近更新 更多