【问题标题】:Using component from Core module使用核心模块中的组件
【发布时间】:2017-06-27 23:51:43
【问题描述】:

我是 Angular2 新手,我在导入(导出)模块时遇到了一些困难。

根据官方风格指南 CoreModule 是:

CoreModule - 应用启动时导入一次,从不导入其他任何地方。

这是否意味着所有从 Core 模块导出的内容将仅在仅导入它的模块中可用?有没有办法让这些东西在某些子模块中可用?我创建虚拟项目只是为了测试这种行为:

虚拟组件:

@Component({
  selector: 'dummy-component',
  template: '<h4>Dummy component</h4>',
})
export class DummyComponent {}

核心模块:

import { DummyComponent } from './dummy.component';

@NgModule({
  declarations : [DummyComponent],
  exports : [DummyComponent]
})

export class CoreModule {}

应用模块(根模块):

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

Home 模块声明 home 组件:

@Component({
  selector: 'home-component',
  template: 
  `
    <h2>Home component</h2>
    <dummy-component></dummy-component>
  `
})
export class HomeComponent {}

当我尝试运行这段代码时,我得到了这个错误:

'dummy-component' is not a known element

【问题讨论】:

    标签: angular


    【解决方案1】:

    如果您想要其他模块中的内容,则将其放入共享模块(功能模块)中。 CoreModule 不是正确的地方。

    是的,您需要将一个模块导入到要使用该模块中的组件、指令或管道的每个模块。

    【讨论】:

    • 如果你有一个使用组件的根级服务怎么办?该组件应该在哪里声明?假设您有一个使用组件的小吃店服务,您希望在整个应用程序中重用该服务。
    • 服务不应该使用组件。组件使用服务。添加一个可以注入服务并订阅服务提供的 observable 的snackbar 组件。
    • 如果要在整个应用程序中重用此类组件,您会将其放置在哪里?还有小吃栏组件订阅了什么样的 observable,你能更具体一点吗?
    • 将组件放置为 AppComponent 的直接子级,以便始终加载它。应用程序中想要使用该组件的每个部分都会注入该服务。该服务提供了一个类似“showMessage(msg:string)”的方法,当被调用时,它会向小吃栏组件订阅的可观察对象发出一个值。抱歉,我手头没有更具体的信息。我使用 Angular 有一段时间了。那里应该有很多例子。
    猜你喜欢
    • 2019-06-17
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 1970-01-01
    • 1970-01-01
    • 2019-09-20
    • 2019-11-02
    • 1970-01-01
    相关资源
    最近更新 更多