Angular 2 Quickstart

时间:2021-01-24 07:25:29

写一个Angular 2的应用最基本的步骤概括为三步:写root组件,启动它(Boostrap),写index.html。

一些关于命名空间的基本知识

把所有代码放入一个立即调用函数中,通过传入一个空对象app,实现对命名空间的隔离,避免了污染全局命名空间。

(function(app) {
app.AppComponent = ....
})(window.app || (window.app = {}));

将要导出的内容添加到app命名空间内,比如我们通过app.AppComponent=...,来将AppComponent导出,其他文件可以通过app对象来使用。

组件 app.component.js

(function (app) {
app.AppComponent =
ng.core.Component({
selector: "#my-app",
template: "<h1>My First Angular 2 App</h1>"
})
.Class({
constructor: function() {}
});
})(window.app || (window.app = {}));

一个组件控制一个视图,严格意义上组件就是class。

它使用NG的core命名空间中的Component方法和Class方法定义。

Angular 2 Quickstart

Component方法:接收一个具有两个属性的对象作为配置参数,selector是选择器(同jQuery选择器),template是渲染视图的内容(html)。

Class方法:接收一个对象,用于实现component,通过给它属性和方法来绑定到视图,定义它的行为(constructor属性是一个函数,用于定义这些行为?)

启动 boot.js

(function  (app) {
document.addEventListener('DOMContentLoaded',function() {
// 页面文档完全加载并解析完毕之后,调用bootstrap方法,传入根组件AppComponent来启动它
ng.platform.browser.bootstrap(app.AppComponent);
});
})(window.app || (window.app = {}));

页面文档完全加载并解析完毕之后,会触发DOMContentLoaded事件,HTML文档不会等待样式文件、图片文件、子框架页面的加载(load事件可以用来检测HTML页面是否完全加载完毕(fully-loaded))。

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Angular 2</title>
<!-- IE required polyfill -->
<script src="node_modules/es6-shim/es6-shim.min.js"></script> <!-- Angular所需的lib -->
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="node_modules/rxjs/bundles/Rx.umd.js"></script>
<script src="node_modules/angular2/bundles/angular2-all.umd.js"></script> <!-- 自己编写的模块 -->
<script src='app/app.component.js'></script>
<script src='app/boot.js'></script>
</head>
<body>
<!-- Angular需要通过selector找到的视图 -->
<div id="my-app">Loading...</div>
</body>
</html>

需要注意的是boot.js要放在app.component.js之后,当Angular调用boot.js的启动程序,它读取AppComponent组件,找到“my-app”选择器,定位到一个id为“my-app”的元素,将template的内容加载到元素里面。

使用npm start来启动程序,在package.json的配置中实际上将npm start命令映射到了启动lite-server服务,它可以监控文件改动,实现自动刷新。

// package.json
{
"name": "angular2-quickstart",
"version": "1.0.0",
"scripts": {
"start": "npm run lite",
"lite": "lite-server"
},
"license": "ISC",
"dependencies": {
"angular2": "2.0.0-beta.0",
"systemjs": "0.19.6",
"es6-promise": "^3.0.2",
"es6-shim": "^0.33.3",
"reflect-metadata": "0.1.2",
"rxjs": "5.0.0-beta.0",
"zone.js": "0.5.10"
},
"devDependencies": {
"lite-server": "^1.3.1"
}
}