代码之家  ›  专栏  ›  技术社区  ›  j-p

角度5,使用子模块中的组件

  •  2
  • j-p  · 技术社区  · 6 年前

    我遇到了一个似乎无法纠正的错误,我将我的应用程序细分为延迟加载效率 以及使用子路由器 "child" ,则,
    我需要使用主应用程序中使用的组件。

    但我正在 以下错误消息

    AccountInfoComponent类型是两个模块声明的一部分

    我的应用程序结构如下所示

    app
    |--components
        |--accountInfo
            |--accountInfo.component.ts
        |--user
            |--user.component.ts
    |--modules
        |--child
            |--child.component.ts
            |--child.module.ts
            |--child.routing.module.ts
    |--app.module.ts
    |--app.routing.module.ts
    

    AccountInfoComponent在主模块中声明(它不是导入到主路由器,而是通过它的选择器调用…)

    因此,我将我的“child”组件移动到它自己的模块中,完成一个路由器(用于儿童)和延迟加载

    我的 "Child.router" 看起来像这样

    import { NgModule } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    
    import { ChildComponent } from './child.component';
    import { ChildProfileComponent } from './child.profile.component';
    
    import { AccountInfoComponent } from '../../components/accountinfo/accountinfo.component';
    
    const childRoutes: Routes = [
        {
            path: '', 
            component: ChildComponent,
            children: [
                {
                    path: '',
                    component: ChildProfileComponent
                },
                {
                    path: 'account',
                    component: AccountInfoComponent 
                }
            ]
        }
    ];
    
    @NgModule({
        imports: [
            RouterModule.forChild( childRoutes )
        ],
        exports: [
            RouterModule
        ]
    })
    export class ChildRoutingModule {}
    

    主要 app.module 声明人 AccountInfoComponent 因为它在用户中使用。组成部分

    我已尝试导入 AccountInfoComponent 在子路由器中,我尝试从主模块导出它。

    问题:如何在多个模块中使用组件?主应用程序和嵌套模块?

    1 回复  |  直到 6 年前
        1
  •  2
  •   David    6 年前

    实际上,您不能在多个模块中声明组件

    您可以创建一个共享模块,其中包含要在多个模块中重用的组件。

    示例中的这个共享模块可以声明并导出 AccountInfoComponent ,以及需要在不同模块中重用的其他组件。

    https://angular.io/guide/ngmodule-faq#sharedmodule

    您可以在共享模块中声明多个组件,也可以为每个组件创建一个模块并有选择地导入它们,这就是angular material所做的( MatButtonModule ,则, MatCheckboxModule ,…)