9.1 路由 初体验 - RLwu/angular-start GitHub Wiki
路由 - 初体验 一个Web应用通常需要切割为多个不同的组件进行实现,然后根据用户的交互行为(通常 是点击),动态地载入不同的组件,根据用户行为选择组件的过程就是路由:
由于Angular2是面向组件的,所以,Angular2的路由其实就是组件之间的路由。
- html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Router</title>
</head>
<body>
<ez-app><img src="img/wait.gif"></ez-app>
<script type="text/javascript" src="lib/angular2.beta.stack.min.js"></script>
</body>
</html>
- css
ez-app{background:#e9e9e9;border-radius:5px;display:block;padding:5px;}
nav{background:#ccc;padding:5px;}
nav b{cursor:pointer;}
h1{padding:10px;border-radius:5px;color:#fff}
ez-video h1{background:#f00;}
ez-music h1{background:#0f0;}
- ts
import {Inject,Component} from "angular2/core";
import {bootstrap} from "angular2/platform/browser";
//引入路由相关类型定义
import {
LocationStrategy,RouteConfig,
ROUTER_DIRECTIVES,ROUTER_PROVIDERS
} from "angular2/router";
//EzVideo组件
@Component({
selector:"ez-video",
template : `
<h3>视频:轻松一刻</h3>
<embed allowscriptaccess="always" height="482" pluginspage="http://get.adobe.com/cn/flashplayer/" flashvars="list=http%3A%2F%2Fus.sinaimg.cn%2F002TFmqWjx06TNSxqGuz0504010000220k01.m3u8%3FKID%3Dunistore%2Cvideo%26Expires%3D1437020410%26ssig%3DNnoWLSjm2v&fid=1034:882b42973162c7ae7acef23bfaccbe8c&logo=2&uid=1971237631" allowfullscreen="true" width="482" quality="high" src="http://js.t.sinajs.cn/t5/album/static/swf/video/player.swf?v1423545453000454353" type="application/x-shockwave-flash" wmode="transparent">
`
})
class EzVideo{}
//EzMusic组件
@Component({
selector:"ez-music",
template : `
<h3>音乐:平凡之路</h3>
<embed src="http://player.yinyuetai.com/video/player/2094298/a_0.swf" quality="high" width="480" height="334" align="middle" allowScriptAccess="sameDomain" allowfullscreen="true" type="application/x-shockwave-flash"> `
})
class EzMusic{}
//EzApp组件 : 路由配置与执行
@Component({
selector:"ez-app",
directives:[ROUTER_DIRECTIVES],
template : `
<nav>
<!--声明路由入口-->
<a [routerLink]="['Video']">video</a> |
<a [routerLink]="['Music']">music</a>
</nav>
<main>
<!--声明路由出口-->
<router-outlet></router-outlet>
</main>
`
})
//路由配置
@RouteConfig([
{path:"/video", component:EzVideo,name:"Video"},
{path:"/music", component:EzMusic,name:"Music"}
])
class EzApp{
constructor(@Inject(LocationStrategy) ls){
ls.pushState = function(){};//simple hack for crash bug.
}
}
//注入路由功能依赖项
bootstrap(EzApp,[ROUTER_PROVIDERS]);