我不明白 Angular NgModules

I don't understand Angular NgModules

我看了一些解释 NgModules 的视频和关于 NgModules 的官方 Angular 文档,但我仍然掌握它是如何工作的。

我知道组件进入 declarations,模块进入 imports,服务进入 providers我还听说自 Angular v6,服务根本不需要声明?)。 我不明白的是什么时候以及为什么要创建 "sub NgModules" 像 auth.module.ts.

谢谢

首先,我强烈建议您通过Angular官方site来更好地理解。 我可以一言以蔽之。

1) 我为什么要创建那些子 NgModule?

你可以实现Lazy-loading.

2)与仅使用 app.modules.ts 相比有什么好处?

您可以在 Angular 中注册您创建的每个东西,并将它们组合在一起。

3)我应该将那些子 NgModule 导入 app.modules.ts 吗?

是的,你必须这样做。但是,如果您正在实施延迟加载,则没有必要这样做。

4)关于 NgModules 我还需要知道其他什么吗?

是的,参考this link or go through the Angular official documentation

Why should I create those sub NgModules?

Angular 遵循 modular structure 以增强代码结构、可读性和可重用性。 引用文档:

NgModules consolidate components, directives, and pipes into cohesive blocks of functionality, each focused on a feature area, application business domain, workflow, or common collection of utilities.

此外,子模块允许您实现 lazy loading

What is the benefit vs using only app.modules.ts?

由于上述原因,

Angular 推荐模块化结构。此外,查看 style guide.

Should I import those sub NgModules into app.modules.ts?

视情况而定。如果你使用路由,你可以延迟加载这些模块,这样就不必将它们导入到根模块中。一旦与此模块关联的 URL 被命中,Angular 将自行执行此操作。当然,您将不得不 configure 这种行为。

Is there any other things I need to know about NgModules?

official docs 上有很多关于 ngModules 的有用文档。事实上,如果不是所有问题,大部分问题都可以通过深入阅读来回答。

NgModule 常见问题解答:https://angular.io/guide/ngmodule-faq