如何从Angular2中的另一个模块继承模块? [英] How to inherit a module from another module in Angular2?

查看:112
本文介绍了如何从Angular2中的另一个模块继承模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在使用Angular 2 final(2.0.0),让我说我创建了一个WidgetsModule,其中包含一些指令和组件,可以帮助我构建我的应用程序,然后将其导入我的AppModule

So I'm using Angular 2 final (2.0.0) and let's say i create a WidgetsModule with a bunch of directives and components that will help me build my application, and then import it in my AppModule

import { NgModule }      from '@angular/core';
import { UniversalModule } from 'angular2-universal';

import { WidgetsModule } from '../../../widgets';
import { App, appRouting } from './';

@NgModule({
  imports:      [
    UniversalModule,
    WidgetsModule,
    appRouting
  ],
  providers:    [ AppPresenter ],
  declarations: [ App ],
  exports:      [ ],
  bootstrap:    [ App ]
})
export class AppModule { }

然后我想在子模块中使用小部件,如HomeModule,CartModule等。如何在不使用小部件的情况下使用小部件必须在每个其他模块中导入WidgetsModule?

Then i want to use widgets in the child modules, like HomeModule, CartModule, etc. How can I make the widgets available without having to import the WidgetsModule in every other Module?

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

import { WidgetsModule } from '../../../widgets';
import { Cart, cartRouting } from './';

@NgModule({
  imports:      [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    WidgetsModule,  //<-- I want to avoid doing this in every module
    cartRouting
  ],
  providers:    [ ],
  declarations: [ Cart ]

})
export class CartModule { }

有没有一种方法可以像使用指令一样完成exports []?

Is there a way to do it like it's done with the directives in the exports[]?

推荐答案

它直接需要访问自己的 WidgetsModule 就像它需要直接访问它自己的 FormsModule 这样或那样)。清理它的一种方法是从 SharedModule export 在多个地方使用的所有模块。然后你可以在任何地方导入 SharedModule

It directly needs access to its own WidgetsModule just like it need direct access to it's own FormsModule (one way or another). One way to clean it up though is to export all the modules that are used in multiple places, from a SharedModule. Then you can just import the SharedModule everywhere

@NgModule({
  exports: [
    FormsModule,
    CommonModule,
    WidgetsModule
  ]
})
class SharedModule {}

您不需要将导入中的任何一个导入 SharedModule 除非您声明使用任何其他模块的 SharedModule 中的组件。

You don't need to imports any of them into the SharedModule unless say you are declaring a component in the SharedModule that uses any of those other modules.

然后在所有其他模块中,只需导入 SharedModule 。这最终会清理它,你只需要维护一个共享模块。

Then in all your other modules, just imports the SharedModule. This ends up cleaning it up a lot, and you only need to maintain one shared module.

另见:

  • Angular2 How to clean up the AppModule

这篇关于如何从Angular2中的另一个模块继承模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆