欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Angular2学习笔记——详解NgModule模块

程序员文章站 2023-11-16 12:56:46
在angular2中一个module指的是使用@ngmodule修饰的class。@ngmodule利用一个元数据对象来告诉angular如何去编译和运行代码。一个模块内部...

在angular2中一个module指的是使用@ngmodule修饰的class。@ngmodule利用一个元数据对象来告诉angular如何去编译和运行代码。一个模块内部可以包含组件、指令、管道,并且可以将它们的访问权限声明为公有,以使外部模块的组件可以访问和使用到它们。

模块是用来组织应用的,通过模块机制外部类库可以很方便的扩展应用,rc5之后,angular2将许多常用功能都分配到一个个的模块中,如:formmodule、httpmodule、routermodule。

ngmodule的主要属性如下:

  • declarations:模块内部components/directives/pipes的列表,声明一下这个模块内部成员
  • providers:指定应用程序的根级别需要使用的service。(angular2中没有模块级别的service,所有在ngmodule中声明的provider都是注册在根级别的dependency injector中)
  • imports:导入其他module,其它module暴露的出的components、directives、pipes等可以在本module的组件中被使用。比如导入commonmodule后就可以使用ngif、ngfor等指令。
  • exports:用来控制将哪些内部成员暴露给外部使用。导入一个module并不意味着会自动导入这个module内部导入的module所暴露出的公共成员。除非导入的这个module把它内部导入的module写到exports中。
  • bootstrap:通常是app启动的根组件,一般只有一个component。bootstrap中的组件会自动被放入到entrycomponents中。
  • entrycompoenents: 不会再模板中被引用到的组件。这个属性一般情况下只有ng自己使用,一般是bootstrap组件或者路由组件,ng会自动把bootstrap、路由组件放入其中。 除非不通过路由动态将component加入到dom中,否则不会用到这个属性。

每个angular2的应用都至少有一个模块即跟模块。

import {ngmodule} from '@angular/core';
import {browsermodule} from '@angular/platform-borwser';
import {appcomponent} from './appcomponent';

@ngmodule({
  declarations: [appcomponent],
  imports: [browsermodule],
  bootstrap: [appcomponent]
})
export class appmodule{}

随着程序的壮大,单一的根模块已不能清晰的划分职责,这时候便可以引入feature module。feature module与根模块的创建方式一样,所有的模块共享一个运行期上下文和依赖注入器。

功能模块与根模块的职责区别主要有以下两点:

  • 根模块的目的在于启动app,功能模块的目的在于扩展app
  • 功能模块可以根据需要暴露或隐藏具体的实现

angular2提供的另一个与模块有关的技术就是延迟加载了。默认情况下angular2将所有的代码打包成一个文件,目的是为了提高应用的流畅性,但是如果是运行在mobile中的app,加载一个大文件可能会过慢,所以rc5提供了一种延迟加载方式。

template: `
 <app-title [subtitle]="subtitle"></app-title>
 <nav>
  <a routerlink="contact" routerlinkactive="active">contact</a>
  <a routerlink="crisis" routerlinkactive="active">crisis center</a>
  <a routerlink="heroes" routerlinkactive="active">heroes</a>
 </nav>
 <router-outlet></router-outlet>
`
import { modulewithproviders } from '@angular/core';
import { routes, routermodule } from '@angular/router';

export const routes: routes = [
 { path: '', redirectto: 'contact', pathmatch: 'full'},
 { path: 'crisis', loadchildren: 'app/crisis/crisis.module#crisismodule' },
 { path: 'heroes', loadchildren: 'app/hero/hero.module#heromodule' }
];

export const routing: modulewithproviders = routermodule.forroot(routes);

其中,path指明路径,loadchildren指明使用延迟加载,'app/crisis/crisis.module#crisismodule'指明了模块的路径,和模块的名称。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。