【问题标题】:Angular 5, using a component in a sub-moduleAngular 5,在子模块中使用组件
【发布时间】:2018-09-24 10:47:51
【问题描述】:

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

但我收到 以下错误消息

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

我的应用结构如下所示

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.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,因为它在user.component 中使用。

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

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

【问题讨论】:

  • 您想将其分解到另一个模块中,然后在两个模块中引用。
  • 我很害怕 - 我有一堆组件,它们必须是它们自己的模块......这很常见吗?
  • 是的,不幸的是它相当普遍。 NgModule 是一个设计糟糕的抽象

标签: angular angular-routing angular-module


【解决方案1】:

确实你不能在多个模块中声明一个组件

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

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

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

您可以在共享模块中声明多个组件,也可以为每个组件创建一个模块并有选择地导入它们,这就是 Angular Material 所做的(MatButtonModuleMatCheckboxModule、...)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-04
    相关资源
    最近更新 更多