【问题标题】:Does @NgModules couples by declaring directives, services etc. at root level?@NgModules 是否通过在根级别声明指令、服务等来进行耦合?
【发布时间】:2017-09-14 19:13:09
【问题描述】:

我刚升级到angular2 RC5,红了这篇关于@NgModules的文章。
https://angularjs.blogspot.de/2016/08/angular-2-rc5-ngmodules-lazy-loading.html

使用@NgModules,组件、指令、服务等在模块根级别上得到声明。我对此的想法是:我们不尝试解耦想法,我们不尝试归档甚至可以被自己使用的构建组件吗?

如果我现在有一个在“容器”组件“Notes”中使用的组件,例如“NoteCard”,该怎么办。

记事卡:

import {Component} from "@angular/core";

@Component({
    selector: 'note-card',
    styleUrls: ['app/ui/note-card/note-card.css'],
    templateUrl: 'app/ui/note-card/note-card.html'
})
export class NoteCard {}

注意事项:

import {Component} from "@angular/core";
import {NoteCard, NoteCreator} from "../../ui";
import {NotesService} from "../../services";

@Component({
    selector: 'notes-container',
    directives: [
        NoteCard
    ],
    styleUrls: ['app/containers/notes/notes.css'],
    templateUrl: 'app/containers/notes/notes.html'
})
export class Notes {}

在 RC4 中,我们只需将“NoteCard”注入“Notes”。这样我们就可以单独使用“NoteCard”(当然它没有依赖项)和“Notes”与“NoteCard”结合使用,因为它是它自己的依赖项。

使用 RC5,我必须将“NoteCard”注入@NgModule 根级别。有了这个,我总是需要一个额外的级别,如果它变得更复杂,它可能会比注入依赖项的位置高几个级别。

在一个项目中使用多个@NgModule 有意义吗?在我的情况下,每个“容器”组件都应该是@NgModule吗?

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    当然,拥有多个模块是有意义的!否则,您将无法使用此新功能的好处。

    请阅读这篇文章:https://angular.io/docs/ts/latest/guide/ngmodule.html

    它很长,是的.. 但是有很多例子,code-sn-ps 和 plunkers。

    在现场演示中,您将看到不同的模块,有时里面只有一个组件,有时还有更多。并且您决定哪些组件对您的模块外部可见(导出)。

    【讨论】:

    • 因为它无处不在,我想我可以把它放在主 app.module 中。我已经有一个共享模块,所以我只是按照你的建议把它放在那里。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    • 2012-11-05
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 2018-11-19
    相关资源
    最近更新 更多