如何创建共享模块

时间:2017-11-20 18:38:18

标签: angular ionic-framework ionic3

全新的Ionic / Angular开发,我有以下结构

- src
-- /app
---- app.component.ts
---- app.module.ts
---- main.ts
---- ...
-- /pages
---- /event-home
------ /event-home.module.ts
------ /event-home.ts

事件home.module.ts

import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { EventHomePage } from './event-home';

@NgModule({
  declarations: [
  EventHomePage,
],
imports: [
    IonicPageModule.forChild(EventHomePage),
],
entryComponents: [
  EventHomePage
]
})
export class EventHomePageModule {}

app.module.ts

import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { EventEntryPage, EventHomePage, EventDiscussionPage, 
EventHandoutsPage, EventInfoPage } from "../pages/pages";

@NgModule({
  declarations: [
    MyApp,
    EventEntryPage,
    EventHomePage,
    EventDiscussionPage,
    EventHandoutsPage,
    EventInfoPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    EventEntryPage,
    EventHomePage,
    EventDiscussionPage,
    EventHandoutsPage,
    EventInfoPage
  ],
  providers: [
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

我正在尝试与http://localhost:8100/#/event-home建立深层链接,在 event-home.ts 中我使用IonicPage()

当我访问网址时,我得到Error: Type EventHomePage is part of the declarations of 2 modules: AppModule and EventHomePageModule! Please consider moving EventHomePage to a higher module that imports AppModule and EventHomePageModule.

认为我需要创建一个共享模块,但我仍然试图围绕如何做到这一点。我开始时喜欢:

import {NgModule} from "@angular/core";
import {EventHomePage} from "../pages/event-home/event-home";

@NgModule({
    declarations: [ EventHomePage ],
    exports: [ EventHomePage ]
})
export class SharedModule {}

但我坚持说,“我现在该怎么办?”如果还不清楚的话,我有点在这里偷看,所以如果我追逐错误的解决方案,请指出。

1 个答案:

答案 0 :(得分:1)

组件只能在一个模块中声明,并且它们的访问权限也不会以任何方式继承,这意味着在主应用程序模块中声明它不会让您在任何其他模块中访问它。如果您有一个其他模块使用的组件,那么您已经注意到了创建共享模块的最佳和唯一方式:

import {NgModule} from "@angular/core";
import {EventHomePage} from "../pages/event-home/event-home";

@NgModule({
    declarations: [ EventHomePage ],
    exports: [ EventHomePage ]
})
export class SharedModule {}

只需在您的核心模块中导入 SharedModule

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

@NgModule({
  imports: [
    SharedModule,
    ...
  ],
  declarations: [
    ...
    ...
  ]
  ...
})
export class AppModule {}

有用的链接: