angular2学习笔记一

现在angular2正式发布了,以前是es6的,现在完全换成了typescript的。
现在先介绍两个比较好的angular2的脚手架。
angular2-seed
angular2-webpack-starter
再来两个bootstrap与angular2的结合比较好的分享
ng2-bootstrap
ng2-admin

不过这些框架都是考虑的相当的全面,不适合刚刚学习,想了解angular2的我,这里还是感觉看官网的比较适合刚开始的学习,需要什么就可以添加什么。这里我们学习一下项目工程的搭建和路由的配置。
angular2官网地址

1.环境配置
我们需要安装node.js。官网说需要node v5.x.x或更高版本以及npm 3.x.x或更高版本。
2.创建项目
需要的配置文件:

  • package.json 用来标记出本项目所需的 npm 依赖包。
  • tsconfig.json 定义了 TypeScript 编译器如何从项目源文件生成 JavaScript 代码。
  • typings.json 为那些 TypeScript 编译器无法识别的库提供了额外的定义文件。
  • systemjs.config.js 为模块加载器提供了该到哪里查找应用模块的信息,并注册了所有必备的依赖包。 它还包括文档中后面的例子需要用到的包。

具体的项目文件详情内容在官网中都有详细的步骤讲解。
这里就不重复了!

3.接下来我们说一下路由的配置
首先我们创建一个路由配置信息的文件app.routing.js

1
2
3
4
5
6
7
8
9
10
11
12
13
import { ModuleWithProviders }  from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { homeComponent } from './home/home.component';
import { aboutComponent } from './about/about.component';

const appRoutes: Routes = [
{ path: '', component: homeComponent },
{ path: 'home', component: homeComponent },
{ path: 'about', component: aboutComponent }
];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

然后我们在app.module.ts中引入路由配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import {NgModule}       from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';

import {AppComponent} from './app.component';
import { routing, appRoutingProviders } from './app.routing';

import { homeComponent } from './home/home.component';
import { aboutComponent } from './about/about.component';

@NgModule({
imports: [
BrowserModule,
routing
],
declarations: [
AppComponent,
homeComponent,
aboutComponent
],
providers: [
appRoutingProviders
],
bootstrap: [AppComponent]
})
export class AppModule {}

这时候运行npm start会出现的错误:

第一种错误是在app.component.ts的template中却少这样的一句代码

1
<router-outlet></router-outlet>

第二种错误是由于no base href set.,所以要在index.html中添加这样一句

1
<base href="/">

关于链接的跳转,我们分页面和controller两块。
页面的写法(只限于a标签):

1
2
<a routerLink="/home">home</a>
<a routerLink="/about">about</a>

写在xx.ts中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
template: `
<h2>home</h2>
<button (click)="goAbout()">跳转到about页面</button>
`
})

export class homeComponent {
constructor(private router:Router) {

}

goAbout() {
this.router.navigate(['about']);
//或this.router.navigateByUrl('about')
}

}