在Angular2中继承从父模块​​到子模块的导入

Lio*_*ion 12 single-page-application angular2-modules angular

我制作了一个像这里描述的Angular2应用程序.它有两个组件(A,B),由全局导入app.module.我的想法是,包含共享模块app.module,所以我不需要用冗余代码搞乱每个模块.我想以此为例FormsModule.所以在app.module我有

imports: [
    UniversalModule,
    CommonModule,
    FormsModule,
    AModule
    RouterModule.forRoot([])
],

exports: [FormsModule]
Run Code Online (Sandbox Code Playgroud)

但是在A模块中,我得到了异常Can't bind to 'ngModel' since it isn't a known property of 'select'.,这似乎是由于缺失造成的FormsModule.它只有在我FormsModule使用时导入每个子模块时才有效imports: [FormsModule].这正是我想要避免的.

根据这个问题,我试图导入AppModule子模块A.这不起作用,并给我例外Exception: Call to Node module failed with error: Error: Unexpected value 'undefined' imported by the module 'AModule'

如何继承子模块的导入?我也需要这个用于管道.

Gün*_*uer 8

只需创建一个功能模块(或共享模块),它可以导出通常一起使用的组件,指令和管道,并将此模块导入要使用其中任何一个的模块.

无法在全球范围内提供组件,指令或管道.需要将它们添加到使用它们的每个模块的导入中.您所能做的就是组合模块,并通过仅导入一个或几个模块使它们可用.


Lio*_*ion 7

似乎这只能使用共享模块来完成,该模块收集共享导入,如@GünterZöchbauer所说.我在官方文档中找到了一个示例,我将其用作创建共享模块的基础:

import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { ObjectKeysPipe } from './../shared/pipes/object-keys.pipe';

@NgModule({
    imports: [CommonModule],
    declarations: [
        ObjectKeysPipe
    ],
    exports: [
        CommonModule,
        FormsModule,
        ObjectKeysPipe
    ]
})
export class GlobalSharedModule{}
Run Code Online (Sandbox Code Playgroud)

这与我(ObjectKeysPipe)共享一个自定义管道,并且广泛使用CommonModuleFormModule.减少还原剂混乱的想法奏效了.在我的应用程序模块中,我不需要添加一堆导入/声明.相反,我只需要像这样导入我的共享模块:

import { GlobalSharedModule } from './../shared/global-shared.module';
@ngModule({
    imports: GlobalSharedModule
})
Run Code Online (Sandbox Code Playgroud)

  • @DouglasGaskell在`compilerOptions`下的`tsconfig.json`然后``paths`你可以声明一个像`"store"这样的路径:["src/store.ts"]`.见[link](https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping) (4认同)