Angular2 小贴士 NgModule 模块

angular2 具有了模块的概念,响应了后台程序的号召,高内聚 低耦合。模块就是用来进行封装,进行高内聚  低耦合的功能。

其实各人认为ng2 的模块和.net的工程类似,如果要使用模块中定义的功能,第一步就是必须要引用它,ng2 中叫import 导入。

那么我们看模块是否有层级概念呢,至少目前来看,模块都是平级的,没有主子之分。

如何定义模块呢?

 1 import { NgModule } from '@angular/core';
 2 import { BrowserModule } from '@angular/platform-browser';
 3 
 4 /* App Root */
 5 import { AppComponent } from './app.component';
 6 
 7 /* Feature Modules */
 8 import { ContactModule } from './contact/contact.module';
 9 import { CoreModule } from './core/core.module';
10 import { routing } from './app.routing';
11 import { Title } from '@angular/platform-browser';
12 @NgModule({
13   imports: [
14     BrowserModule,
15     ContactModule,
16     /*
17         CoreModule,
18     */
19     CoreModule.forRoot({ userName: 'Miss Marple' }),
20     routing
21   ],
22   declarations: [AppComponent],//声明当前模块需要的指定 组件信息
23   exports:[],
24   providers: [Title],
25   bootstrap: [AppComponent]
26 })
27 export class AppModule { }

 

简单说明一下模块元数据中各个参数的用途。

imports:导入其他模块,就是要使用其他模块的功能,必须要导入。

declarations:声明,声明本模块包含的内容。可能有些同学会遇到,定义了一个指令,在component中使用却总是没有生效的问题,首先我们要检查的就是是否进行了声明。

exports:外部可见的内容。相当于.net中声明为public的那些类。

providers:服务提供者,主要用来定义服务。估计ng2框架会自动将注册的服务体检到依赖注入实例中,目前测试也是如此。

bootstrap:启动模块。只在根模块使用。在除了根模块以外的其他模块不能使用。

 

2.问题2

目前官方叫法:启动模块为根模块,自定义的其他模块叫特性模块。

我们是否可以在特性模块中import根模块呢?

实验是检验真理的最好方法。

 1 import { NgModule }           from '@angular/core';
 2 import { SharedModule }       from '../shared/shared.module';
 3 
 4 import { ContactComponent }   from './contact.component';
 5 import { ContactService }     from './contact.service';
 6 import { routing }            from './contact.routing';
 7 import{GuozhiqiModule}from '../directives/guozhiqi.module';
 8 import{AppModule}from '../app.module';
 9 @NgModule({
10   imports:      [ SharedModule, routing,GuozhiqiModule,AppModule ],// 导入模块
11   declarations: [ ContactComponent ],//声明 指令  
12   providers:    [ ContactService ]//服务提供者 在当前模块提供者中注册当前模块需要的服务
13 })
14 export class ContactModule { }

 

appModule是根模块,我们定义的contactModule是特性模块,现在我们通过imports 导入根模块。

 

执行出现错误,contactModule导入了一个undefined的module?

为什么会出现这个问题呢?

各人估计是因为1.导致了循环引用的问题。appModule会加载ContactModule,而在ContactModule中又要import 根模块,导致循环引用,从而出现错误。

2.另一种解释就是根模块不允许导入。ng2框架不允许这样

问题3:如何避免出现循环引用呢?

官方给出了答案:https://angular.cn/docs/ts/latest/guide/ngmodule.html#!#prevent-reimport

1 constructor (@Optional() @SkipSelf() parentModule: CoreModule) {
2     if (parentModule) {
3       throw new Error(
4         'CoreModule is already loaded. Import it in the AppModule only');
5     }
6   }

 

但是我本地验证并不会有效的验证如何避免重复import一个模块。

问题4. 模块与路由的关系。

基本上每个特性模块都有单独的路由定义,关于模块和路由的关系定义,下次说到ng2路由时再细说,因为ng2的路由太强大,以至于需要很长时间的理解才能明白。

 

ng2模块的目录和目录结构的最佳实践:

1.每个模块一个单独的文件夹

2.模块是高内聚 低耦合

3.模块内功能相关或相近

4.每个模块都有单独的路由定义 -不是必须

5.不要重复导入一些模块,必要的时候加入限制。 因为重复导入可能会影响依赖注入实例

 

posted @ 2016-10-19 01:48  baidixing  阅读(3629)  评论(1编辑  收藏  举报