Angular2模块

Angular 2 模块

描述

Angular中的应用遵循模块化结构。 Angular应用程序将包含许多模块,每个模块专用于单一目的。 通常模块是一个连贯的代码组,它与其他模块集成以运行Angular应用程序。

模块从其代码中导出一些类,函数和值。 组件是Angular的基本块,多个组件将构成您的应用程序。

模块可以是另一个模块的库。 例如,作为主Angular库模块的 angular2 / core 库将由另一组件导入。

例子

下面的例子描述了在Angular 2中使用模块:

<!DOCTYPE html>

<html>

<head>

<title>Angular 2 Modules</title>

<script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/es6-shim.min.js"&gt;&lt;/script&gt;

<script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/system-polyfills.js"&gt;&lt;/script&gt;

<script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/angular2-polyfills.js"&gt;&lt;/script&gt;

<script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/system.js"&gt;&lt;/script&gt;

<script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/typescript.js"&gt;&lt;/script&gt;

<script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/Rx.js"&gt;&lt;/script&gt;

<script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/angular2.dev.js"&gt;&lt;/script&gt;

<script>

System.config({

transpiler: 'typescript',

typescriptOptions: { emitDecoratorMetadata: true },

packages: {'app': {defaultExtension: 'ts'}}

});

System.import('/angular2/src/app/modules_main')

.then(null, console.error.bind(console));

</script>

</head>

<body>

<my-app>Loading...</my-app>

</body>

</html>

上述代码包括以下配置选项:

    您可以使用 typescript 版本配置 index.html 文件。  在使用 transpiler 选项运行应用程序之前,SystemJS将TypeScript转换为JavaScript。

如果在运行应用程序之前没有翻译到JavaScript,您可能会看到浏览器中隐藏的编译器警告和错误。

当设置了 emitDecoratorMetadata 选项时,TypeScript会为代码的每个类生成元数据。 如果不指定此选项,将生成大量未使用的元数据,这会影响文件大小和对应用程序运行时的影响。

Angular 2包含来自 app 文件夹的包,其中文件将具有 .ts 扩展名。

接下来,它将从 app 文件夹加载主组件文件。 如果没有找到主要组件文件,那么它将在控制台中显示错误。

当Angular调用main.ts中的引导函数时,它读取Component元数据,找到“app"选择器,定位一个名为app的元素标签,并在这些标签之间加载应用程序。

要运行代码,您需要在 app 文件夹下需要保存以下 TypeScript(.ts)文件。

modules_main.tsimport {bootstrap} from "angular2/platform/browser" //importing bootstrap function

import {MyModulesClass} from "./modules_app.component" //importing component function

bootstrap(MyModulesClass);

现在我们将在TypeScript(.ts)文件中创建一个组件,我们将为该组件创建组件和视图。

modules_app.component.tsimport {Component, View} from "angular2/core";

//framework recognizes @Component annotation and knows that we are trying to create a new component

@Component({

selector: 'my-app'

})

@View({

//this template value will be displayed in the browser

template: '<h2>Welcome to Tutorialspoint</h2>'

})

export class MyModulesClass { }

输出

当您运行上述代码时,它将显示在 modules_app.component.ts 文件中定义的 template 选项中指定的文本。 让我们执行以下步骤,看看上面的代码如何工作:

    将上面的HTML代码保存为index.html文件,如同我们在环境章节中创建的,并使用上面的包含.ts文件的应用程序文件夹。

打开终端窗口并输入以下命令:

npm start

稍后,浏览器选项卡应打开并显示输出,如下所示。

或,您可以以其他方式运行此文件:

    将上述HTML代码另存为服务器根文件夹中的 angular2_modules.html 文件。

将此HTML文件打开为http://localhost/angular2_modules.html,并显示如下所示的输出。