Angular4中的共享模块是什么

  介绍

这篇文章将为大家详细讲解有关Angular4中的共享模块是什么,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

<强> 1。AppModule

@NgModule ({,,   声明才能:,,,   ,,,AppComponent ,   ,,,,,   进口才能:,,,   ,,,BrowserModule ,   ,,,,,   出口:,才能,AppComponent ,,,   ,,提供者:[],,,   ,,引导:[AppComponent],,   }),,   {export  class  AppModule }

进口本模块声明的组件模板需要的类所在的其它模块。
提供者服务的创建者,并加入到全局服务列表中,可用于应用任何部分。
声明声明本模块中拥有的视图类.Angular有三种视图类:组件,指令和管道。
出口声明的子集,可用于其它模块的组件模板。
引导指定应用的主视图(称为根组件),它是所有其它视图的宿主。只有根模块才能设置引导属性。

<强> 2。CommonModule

先看一下CommonModule中有什么内容。

 Angular4中的共享模块是什么”> <br/> </p> <h4> common.module。ts代码</h4> <pre类= @NgModule ({   进口:,才能   ,,,NgZorroAntdModule,   ,,AngularCommonModule   ,,,   声明:,才能   ,,,CommonComponent,   ,,,NumberFilterPipe,   ,,,ButtonDirective,   ,,StepComponent   ,,,   ,,出口:[   ,,,CommonComponent,   ,,,NumberFilterPipe,   ,,,ButtonDirective,   ,,StepComponent   ,,,   供应商:,才能      ,,,   })

我通常在文件夹中创建了服务、管、组件,指令,但是这个服务和这没个模块有任何关系。至于服务会在下面说到,然后将烟斗,组件,指令输出,这样其他模块才能使用。

<强> 3。AngularModule

然后我们需要在其他的模块中使用这个模块,就需要导入进来。

import  {, NgModule },得到& # 39;@angular/核心# 39;;   {},AngularComponent  import 得到& # 39;。/angular.component& # 39;;   import } {RouterModule,路线,得到& # 39;@angular/路由器# 39;;   import  {CommonModule  as  CommonPrivateModule},得到& # 39;. ./. ./共同/common.module& # 39;;   import  {CommonModule},得到& # 39;@angular/常见# 39;;   {HttpService}因为import 得到& # 39;. ./. ./共同/服务/http.service& # 39;;   import  {HttpCommonService},得到& # 39;. ./. ./共同/服务/http-common.service& # 39;;   import  {BrowserModule},得到& # 39;@angular/platform-browser& # 39;;      路线:const  Routes =, (   {才能路径:& # 39;& # 39;,,组件:,,AngularComponent}   ];      @NgModule ({   进口:,才能   ,,,CommonModule,   ,,,RouterModule.forChild(路线),   ,,CommonPrivateModule   ,,,   ,,声明:[AngularComponent],   ,,提供者:[]   })   {export  class  AngularModule }

因为CommonModule与系统内的模块重名,所以我重命名为CommonProvateModule。这样我们就可以在AngularModule中使用共享模块的内容。

angular.component.html

& lt; p>   & lt;才能app-step  [stepString]=癧& # 39; common 组件# 39;]“祝辞& lt;/app-step>   & lt;才能button  appButton>, common  directive, & lt; br>   common 才能管:{{1,|,numberFilter}}   & lt;/p>

这个html文件中我使用了之前创建的StepComponent, NumberFilterPipe, ButtonDirective。

<强> 4。服务

服务前面在常见的文件加下,但是没有在CommonModule提供。这是为什么呢,因为服务靠角的依赖注入体系实现的,而不是模块体系。如果我们在CommonModule提供,那么我们在各个模块使用的服务不是一个实例,而是多个实例。下面我们就来测试一下。

先说一下例子的模块结构,AppModule, HomeModule (AppModule的子模块),AngularModule (HomeModule的子模块),然后分别在三个模块中引入CommonModule。

修改一下上面的CommonModule,将HttpCommonService提供出去。

@NgModule ({   进口:,才能   ,,,NgZorroAntdModule,   ,,AngularCommonModule   ,,,   声明:,才能   ,,,CommonComponent,   ,,,NumberFilterPipe,   ,,,ButtonDirective,   ,,StepComponent   ,,,   ,,出口:[   ,,,CommonComponent,   ,,,NumberFilterPipe,   ,,,ButtonDirective,   ,,StepComponent   ,,,   供应商:,才能   ,,HttpCommonService   ,,,   })

Angular4中的共享模块是什么