如何在angular2中使用sharedModule?

时间:2016-09-22 05:28:43

标签: angular typescript angular2-modules ng-modules

我有一个angular2组件,我想在多个模块之间共享。

所以我写了下面的sharedModule,

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {GenericComponent} from './generic/generic.component';
@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ GenericComponent ],
  exports:      [ GenericComponent ]
})
export class SharedModule { }

然后我将这个sharedModule添加到多个模块中,如下所示:

app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {SharedModule} from './shared.module';
import { AppComponent } from './app.component';
@NgModule({
  imports:      [ BrowserModule,SharedModule ],
  declarations: [ AppComponent ],
  exports:      [ AppComponent ],
  bootstrap: [AppComponent]
})
export class AppModule { }

我同样将sharedModule添加到generic.module.ts,

generic.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {SharedModule} from './shared.module';
@NgModule({
  imports:      [ BrowserModule,SharedModule ],
  declarations: [ //.. here I have added all the components that generic uses ]
})
export class GenericModule { }

但是当我尝试在generic.module.ts的组件中使用泛型组件时,我遇到了以下错误

  

模块'GenericModule'

导入的意外值'undefined'

2 个答案:

答案 0 :(得分:6)

这是我的应用程序使用共享模块的代码:

应用模块:

String yourFilePath = context.getFilesDir() + "/" + "hello.txt";
File file = new File( yourFilePath );
if(file.exists()) 
{
} 

家庭模块:

import { AboutModule } from './about/about.module';
import { SharedModule }   from './shared/shared.module';
import { Menubar, MenuItem } from 'primeng/primeng';

@NgModule({
    imports: [ BrowserModule, RouterModule.forRoot(appRoutes), SharedModule.forRoot(), 
               HomeModule ],
    declarations: [ AppComponent ],
    bootstrap: [ AppComponent ],
    providers: [ appRoutingProviders ]

}) 

export class AppModule {} 

共享模块:

import { SharedModule }   from '../shared/shared.module';
import {routing} from './home.routing'


@NgModule({
    imports: [ SharedModule, routing],
    declarations: [ HomeComponent, LoginComponent, RegisterComponent, VerifyComponent, 
                   VerifyEmailComponent, ForgotComponent, ForgotVerifyComponent, 
                   ChangeComponent, ChallengeComponent, LogoutComponent ], 
    bootstrap: [ HomeComponent ],
    providers: [ ]

}) 

export class HomeModule {} 

我的应用程序中有20多个模块,我在整个地方使用共享模块。这很好用。希望它有所帮助。

答案 1 :(得分:3)

您无法在featureModule中使用 BroswerModule 。因此,请确保使用 CommonModule ,而不是使用 BrowswerModule

import { NgModule }      from '@angular/core';
import { CommonModule }        from '@angular/common';
import {SharedModule} from './shared.module';
@NgModule({
  imports:      [ CommonModule ,SharedModule ],
  declarations: [ //.. here I have added all the components that generic uses ],
  exports:      [ CommonModule]
})
export class GenericModule { }