【问题标题】:Angular4 module scopes not workingAngular4模块范围不起作用
【发布时间】:2017-12-12 19:45:48
【问题描述】:

我是 Angular 的新手,虽然使用 AngularJs 已经有一段时间了。我决定过渡到 Angular 并一直关注 the style guide

我已经这样设置了我的模块(为简洁起见,我没有显示我的组件,但它们应该是不言自明的)

/app.module.ts

/core/core.module.ts

/data/data.module.ts

/directives/directives.module.ts

/home/home.module.ts

/results/results.module.ts

所以基本上,我使用 core 模块来处理所有其他模块。它看起来像这样:

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';

import { DataModule } from '../data/data.module';
import { DirectivesModule } from '../directives/directives.module';
import { HomeModule } from '../home/home.module';
import { SharedModule } from '../shared/shared.module';
import { QuestionModule } from '../question/question.module';
import { ResultsModule } from '../results/results.module';

import { HomeComponent } from '../home/home.component';
import { ResultsComponent } from '../results/results.component';

@NgModule({
  imports: [
    DataModule,
    DirectivesModule,
    SharedModule,

    HomeModule,
    QuestionModule,
    ResultsModule,

    RouterModule.forRoot([
      { path: 'results', component: ResultsComponent },
      { path: 'home', component: HomeComponent },
      { path:'', redirectTo: 'home', pathMatch: 'full' }
    ])
  ],
  declarations: []
})
export class CoreModule { }

在我的 app 模块中,我试图保持它的小,所以它看起来像这样:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';

import { CoreModule } from './core/core.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent   
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    CoreModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

问题是,当我运行我的网站时,我收到错误消息,指出找不到 question 组件。 此外,它还抱怨我的指令也找不到。

我认为在它们各自的模块中声明组件/指令并将所有模块导入核心模块,然后将其导入应用模块将允许所有组件访问指令等。

应用程序组件使用数据服务并且工作正常,所以我只是不明白为什么其他人都失败了。

有人可以帮我吗?

【问题讨论】:

  • CoreModule 中的模块应该在 AppModule 中。正如您在样式文档中所读到的,您主要使用 CoreModule 添加应该具有单例实例的提供程序。如果您仍需要澄清,请告诉我

标签: angular


【解决方案1】:

我想你忘了export 组件了你的模块。即在模块定义中,您必须再提供一个导出数组

exports:[coponent want to export]

所以在 questionmodule 中你必须写这个。

@NgModule({
  declarations: [QustionComponent, other component],
  imports: [module toimport ],
  providers: [service provider],
  exports:[QuestionComponent, other coponent you want to export ]
})

【讨论】:

    【解决方案2】:

    在 Angular 中,您必须导出可以重复使用的组件。

    例如,指令、组件和管道是可以重复使用的组件。

    如果您希望它工作,只需在您的相关模块(即 CoreModule 和 DirectivesModule)中添加一个 exports 属性,该属性将包含您的 QuestionComponent,所有指令。

    (请记住,您需要导出导入的组件;这意味着您必须先在同一个模块中导入它)

    【讨论】:

    • 我错了,但你不能导入组件/指令?你的意思是你必须先将它添加到声明中?
    • 不,你是对的,我写得太快了。您需要声明它,而不是导入它!导入是针对模块的,我的错。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    相关资源
    最近更新 更多