|
Post by account_disabled on Jan 25, 2024 7:22:23 GMT
NgModule 是 Angular 中的一个核心概念,它是每个应用程序的一部分,有助于连接编译器和应用程序运行时的一些重要细节。它们对于将代码组织成功能、延迟加载路线以及创建可重用库特别有用。 在本指南中,我们将通过一些示例介绍 NgModules 的主要用途,向您展示如何在 Angular 项目中使用它们!本指南假设您具备 Angular 的应用知识。 JavaScript 模块不是 NgModule 首先让我们澄清一下什么是 JavaScript 模块(有时称为 ES6 模块)。它们是一种语言构造,可以更轻松地组织代码。 最基本的,Javascript 模块是包含import或export关键字的 JavaScript 文件,这会导致该文件内部定义的对象是私有的,除非您将其导出。我鼓励您查看上面的链接以更深入地理解,但本质上这是一种组织代码并轻松共享代码的方法,而不需要依赖可怕的全局范围。 当您使用 TypeScript 创建 Angular 应用程序时,无论何时使用import或export在源中使用,它都会被视为 JavaScript 模块。 能够为您处理模块加载。 Learn to Code with JavaScript 注意:为了让本文的内容更加清晰,我将始终使用 JavaScript 模块和 NgModule 的全名。 基本 NgModule、AppModule 让我们首先看一下每个 Angular 应用程序中都存在的基本 NgModule AppModule(在任何新的 Angular 应用程序中默认生成)。它看起来就像你在这里看到的那样 使用装饰器来定义编译时需要了解的元数据。要定义 NgModue,只需@NgModule()在类上方添加装饰器 WhatsApp 号码数据 即可。班级可能并不总是空的,但通常都是空的。但是,您需要定义一个具有某些属性的对象,以便 NgModule 执行任何操作。 当应用程序引导时,需要为其提供一个 NgModule 来实例化。如果您查看应用程序的主文件(通常也称为main.ts),您将看到platformBrowserDynamic().bootstrapModule(AppModule),这就是应用程序注册和启动 的方式AppModule(可以命名为任何名称,但几乎总是这样命名)。 的属性 NgModule API文档页面概述了定义 NgModule 时可以传递的属性,但我们也将在这里介绍它们。它们都是可选的,但您需要至少为其中之一定义值,以便 NgModule 执行任何操作。 providers 这是一个数组,其中包含可用于此 NgModule 的任何提供程序providers(可注入服务)的列表。提供程序有一个范围,如果它们列在延迟加载的 NgModule 中,则它们在该 NgModule 之外不可用。 Learn to Code with JavaScript declarations 该declarations数组应包含此 NgModule 定义的任何指令、组件或管道的列表。这使得编译器可以找到这些项目并确保它们正确捆绑。如果这是根 NgModule,则声明可用于所有 NgModule。否则,它们仅对同一个 NgModule 可见。 imports 如果您的 NgModule 依赖于另一个 NgModule 中的任何其他对象,则必须将其添加到数组中imports。这可确保编译器和依赖项注入系统了解导入的项目。
|
|