Angular2中包含了一個(gè)路由框架,我們只需要定義一個(gè)個(gè)的路徑和它對(duì)應(yīng)的組件,然后在頁(yè)面跳轉(zhuǎn)時(shí)也是用Angular2的方式就能很方便的實(shí)現(xiàn)路由控制。
Angular2的路由包含下面4個(gè)部分:
- 路由定義
- 路由器
- 導(dǎo)航
- 參數(shù)
路由定義
路由定義,通俗來(lái)講就是定義一個(gè)URL路徑,打開(kāi)的是哪個(gè)頁(yè)面,由哪個(gè)組件來(lái)控制數(shù)據(jù)交互和用戶交互,頁(yè)面就是組件定義中定義的這個(gè)組件對(duì)應(yīng)的模板頁(yè)面。
路由器
路由器也就是分發(fā)器。當(dāng)點(diǎn)擊一個(gè)鏈接時(shí),就是由他來(lái)確定要打開(kāi)哪一個(gè)組件?怎么封裝?怎么傳遞參數(shù)。
導(dǎo)航
就是指從一個(gè)頁(yè)面打開(kāi)另一個(gè)頁(yè)面。有兩種方式:
- 通過(guò)頁(yè)面上的一個(gè)鏈接link
- 在JS中使用代碼導(dǎo)航
參數(shù)
當(dāng)我們?cè)陧?yè)面之間跳轉(zhuǎn)時(shí),通常都需要傳遞參數(shù)。除了常見(jiàn)的URL參數(shù)傳遞之外,在REST風(fēng)格的路徑設(shè)計(jì)中,經(jīng)常使用某一個(gè)id作為url的一部分。
最簡(jiǎn)單的路由配置
S1:設(shè)置index.html頁(yè)面的基址
打開(kāi)index.html
,確保它的<head>區(qū)頂部有一個(gè)<base href="...">
元素(或動(dòng)態(tài)生成該元素的腳本)。
S2:告訴路由器當(dāng)用戶點(diǎn)擊鏈接時(shí),應(yīng)該顯示哪個(gè)視圖?
- 在
app.module.ts
中導(dǎo)入RouterModule
類,并在import數(shù)組中添加路徑導(dǎo)航如下:
RouterModule.forRoot([
{
path: 'heroes',
component: HeroesComponent
}
])
- 路由出口
我們必須告訴路由器它位置,所以我們把<router-outlet>
標(biāo)簽添加到模板的底部。 RouterOutlet
是由RouterModule
提供的指令之一。 當(dāng)我們?cè)趹?yīng)用中導(dǎo)航時(shí),路由器就把激活的組件顯示在<router-outlet>
里面。
- 路由器鏈接
導(dǎo)航的標(biāo)準(zhǔn)化配置
S1:在src下新建導(dǎo)航模塊
app-routing.module.ts
S2:在文件中導(dǎo)入需要加入路由的組件和路由功能依賴的組件
import { NgModule } from '@angular/core';
import { HeroDetailComponent } from './hero-detail/hero-detail.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { HeroesComponent } from './heroes/heroes.component';
// 添加路由功能支持
import { RouterModule, Routes } from '@angular/router';
// 添加path依賴
const routes: Routes = [
{
path: 'heroes',
component: HeroesComponent
},
{
path: 'dashboard',
component: DashboardComponent
},
{
path: '',
redirectTo: '/dashboard',
pathMatch: 'full'
},
{
path: 'herodetail/:id', //帶參數(shù)或者令牌的路由path
component: HeroDetailComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
S3: 在app.module.ts中添加支持
// 1. 導(dǎo)入路由模塊
import { AppRoutingModule } from './app-routing.module';
...
//在import數(shù)組中添加模塊
AppRoutingModule //導(dǎo)入路由模塊
S4-1:在html中引入方式
<nav>
<a routerLink='/dashboard' routerLinkActive="active">儀表盤</a>
<a routerLink='/heroes' routerLinkActive="active">英雄列表</a>
</nav>
<router-outlet></router-outlet>
S4-2:在ts中使用的方法
1. 導(dǎo)入Router路由器組件
import { Router } from '@angular/router';
2. 在constructor中注入路由器實(shí)例
constructor(
private heroServce: HeroService,
private router: Router) { }
3. 在函數(shù)中添加使用,執(zhí)行函數(shù)后會(huì)導(dǎo)航到指定的組件頁(yè)面
gotoDetail(): void {
this.router.navigate(['/herodetail', this.selectedHero.id]);
}