@alexhuang
2016-09-14T02:58:16.000000Z
字数 5839
阅读 1641
技术笔记 TypeScript Angular Sonic
TypeScript 和 JavaScript.
任意js都是合法的TypeScript
interface Animal {name: string;age: number;locality?: string;}// 类型定义时用 ':' 和 ';' key:value; 的形式// 而在export component或者module时候,用key = value;的形式// 在创建实体对象时用{key:value,key2:value2}的形式function f(x: Animal) {return x.name;}var n:string = f({name: 'Benj', age: 3});// typeScript 有函数缺省参数检测function createVM(os:string, version: number,hasFloopy: bool =false,FileName: string = hasFloopy? 'BOOT.ING': null {setName(os + version.toString());if (FileName) {load(FileName);}}// 完全长得像C# 。typescript有点像以C# 的方式来写JS,最终编译为原生 JavaScript// 并且上面这段代码在编译之后会变为带 参数检测的。undefined 表示有declare,但没有赋值的变量if (typeof hasFloopy === 'undefined') {hasFloopy = false;}if (typeof FileName === 'undefinded') {// ....}
Arrow记号作为匿名函数的快捷方式,节省代码,并且可以避免this指向的错误。在没有箭头符号之前,可采用var that = this; 的办法正确指向。
// 和ES6类似的Arrow. 使用回调函数的场合,容易犯错的是this的作用域。var tickIncreaser = {tick: 0,increase: function() {window.onclick = (e) => {alert((this.tick++).toString());}}}// 以上Script经过编译后//...increase: function () {// 将上下文环境保留在_this 变量中。var _this = this;window.onclick = function (e) {alert((_this.tick++).toString))}}//../* 构造函数 */class Human {constructor(public name:string, public age:number){static baseSalary = 1500;static baseAge = 18;}printSalary(){var salary = this.age < 18 ? 0: Human.baseSalary + this.age - (Human.baseAge) * 200;alert('Salary of' + this.name + 'is ' + salary.toString());}}var h1 = new Human('jack', 20);var h2 = new Human('ross', 17);h1.printSalary();h2.printSalary();// class 是立即执行函数, 等效于 var Human = (function(){...})() 这个在《JS设计模式和编程实践》中有讲到.// TypeScript 符合ES6的标准,支持存取器。get Salary(){return salary;}h1.getSalary() // 可以获取salary属性
可以看到TypeScript 很类似于静态语言,有类型检测等特性。并且实现了ES6的许多特性,包括export,class,Arrow匿名函数等等。实现了模块化的管理方式,更加方便重构(refactor).
Angular2 还处于快速更新中,所以版本存在不稳定。2016年8月最新版核心组件@angular/core的版本号是rc.5. 比上一版本新增了 ngModule 核心组件,管理declaration等等。 并且@angular/router也有所更新,rc.1,包含了RouteModule等关键组件。
根组件(app.component)和根模块(app.module),一个web应用至少需要一个根组件和一个根模块。根组件包含路由,服务!在root层面注册服务和路由singleton,使得子组件都可以用到同样的服务和路由。
根模块注册了declaration,并导入了可选模块:form, router 等等。
几个关键词:
import { Component } from '@angular/core';
@Component({
selector: '',
styles:,
templates:
})export class yourComponent {
title=;
//...
}
根据单一职责原则 一个数据模型或者组件的职责应该是单一的,这样才可以实现非耦合,方便组件化。
创建一个自定义component需要 IMport,装饰器,以及export为自定义组件。三个基本部分。
template synTax:
// onSelect() come from export function// [(ngModel)]='selectedHero.name' two-way-binding.// properties we used in the templates come from the exported component!@Component({templates:`<li *ngFor='let hero of heroes'[class.selected]='hero === selectedHero'(click)='onSelect(hero)'<div *ngIf='selectedHero'><input [(ngModel)]='selectedHero.name'>`})
Separating the Component:
to connect two component ,and implement the variable share. property bind is required.
For instance: selectedHero comes from the user operation, and change the property of appComponent(list). how to pass the selected hero to the detailComponent?!
@Input 装饰目标变量,表明这个变量的值由外部传入
/* use @Input to annotate the hero to be Input property.* receive value from other Component.*/export class HeroDetailComponent {@Input()hero: Hero;// present the property "hero" is type Hero;}// 在source组件中赋值// 在source中注册 directive@Component({templates:`<target [hero]='selectedHero'></target>`directives: [target组件类名];})
@Injectable 装饰可注入的对象,一般表明service可注入组件
// 整个服务是可用于注入的。@Injectable()export class HeroService {getHeroes() {return Promise.resolve(HEROES);}getHeroesSlowly() {return new Promise<Hero[]>(resolve =>setTimeout(() => resolve(HEROES), 2000));}}// 在调用服务的组件中注册providersproviders: [HeroService]export class ** implements OnInit {// 在构造函数中实例化服务constructor(private heroService: HeroService) {}getHeroes() {this.heroService.getHeroes().then(heroes => {});}ngOnInit() {this.getHeroes();}}
创建项目文件夹,定义包的依赖以及特别的项目设置
创建根组件(AppComponent)
创建一个Angular模块 ?? (不一定需要)
添加main.ts 配置组件信息
import { bootstrap } from '@angular/platform-browser-dynamic';import { AppComponent } from './app.component';bootstrap(AppComponent);
添加index.html, 宿主页面. 可用import导入模块
<html><head><title>Angular 2 QuickStart</title><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><link rel="stylesheet" href="styles.css"><!-- 1. Load libraries --><!-- Polyfill(s) for older browsers --><script src="node_modules/core-js/client/shim.min.js"></script><script src="node_modules/zone.js/dist/zone.js"></script><script src="node_modules/reflect-metadata/Reflect.js"></script><script src="node_modules/systemjs/dist/system.src.js"></script><!-- 2. Configure SystemJS --><script src="systemjs.config.js"></script><script>System.import('app').catch(function(err){ console.error(err); });</script></head><!-- 3. Display the application --><body><my-app>Loading...</my-app><!-- When Angular calls the bootstrap function in main.ts,it reads the AppComponent metadata, finds the my-app selector,locates an element tag named my-app, and renders our application'sview between those tags. --></body></html>
添加main.ts配置组件信息
import { bootstrap } from '@angular/platform-browser-dynamic';import { HeroesComponent } from './heroes.component';bootstrap(HeroesComponent);// 以上是main.ts, 设定了 根组件的位置,并启动根组件。// Systemjs.config.js(function(global) {// packages tells the System loader how to load when no filename and/or no extensionvar packages = {'app': { main: 'main.js', defaultExtension: 'js' },'rxjs': { defaultExtension: 'js' },'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },};})
在index.html中 import('app') 实际上启动的是 main.js 中的命令,追溯到其中,其实执行的是 bootstrap(HeroesComponent); 启动了整个应用的root组件,或者路由器!!
// 而在index.html中引入的systemjs.config.js中<script src="systemjs.config.js"></script><script>System.import('app').catch(function(err){ console.error(err); });</script><!-- 3. Display the application --><body><my-heroes>Loading...</my-heroes></body>
构建并运行应用(因为typescript可以开启watch transpile 模式,所以文件修改后自动编译为原生js,在页面中可看到修改结果)
由于phantomjs经常安装不上,则采用替换镜像的方法。
npm install phantomjs --registry=https://registry.npm.taobao.org