這篇文章主要介紹了Angular 5.x之Router怎么用,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
實例講解
運行結果如下。 設置了3個導航欄, Home、 About、Dashboard。 點擊不同的導航欄,跳轉到相應的頁面:

創建3個 component
ng g c home
ng g c about
ng g c dashboard
路由與配置
(1)**引入 Angular Router **
當用到 Angular Router 時,需要引入 RouterModule,如下:
// app.module.ts
import { RouterModule } from '@angular/router';
imports: [
BrowserModule, RouterModule
],(2) 路由配置
還記得由誰來管理component 的吧,沒錯,由 module 來管理。 所以,把新創建的 component,引入到 app.moudle 中。 如下:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { appRoutes } from './routerConfig';
import { AppComponent } from './app.component';
import { AboutComponent } from './components/about/about.component';
import { HomeComponent } from './components/home/home.component';
import { DashboardComponent } from './components/dashboard/dashboard.component';提示: 注意component的路徑,為便于管理,我們把新創建的component 移到了 components 文件夾中。
創建 Router Configure 文件
在 app 目錄下, 創建 routerConfig.ts 文件。 代碼如下:
import { Routes } from '@angular/router';
import { HomeComponent } from './components/home/home.component';
import { AboutComponent } from './components/about/about.component';
import { DashboardComponent } from './components/dashboard/dashboard.component';
export const appRoutes: Routes = [
{ path: 'home',
component: HomeComponent
},
{
path: 'about',
component: AboutComponent
},
{ path: 'dashboard',
component: DashboardComponent
}
];說明: Angular 2.X 以上版本,開始使用 TypeScript 編寫代碼,而不再是 JavaScript,所以,文件的后綴是: ts 而不是 js
這個 routerConfigue 文件,怎么調用呢? 需要把它加載到 app.module.ts 中,這是因為 app.moudle.ts 是整個Angular App 的入口。
// app.module.ts
import { appRoutes } from './routerConfig';
imports: [
BrowserModule,
RouterModule.forRoot(appRoutes)
],聲明 Router Outlet
在 app.component.html 文件中,添加代碼:
<div >
<h2>
{{title}}!!
</h2>
<nav>
<a routerLink="home" routerLinkActive="active">Home</a>
<a routerLink="about">About</a>
<a routerLink="dashboard">Dashboard</a>
</nav>
<router-outlet></router-outlet>
</div>運行
進入到該工程所在的路徑, 運行;
ng serve --open
當 webpack 編譯成功后,在瀏覽器地址欄中,輸入: http://localhost:4200
即可看到本篇開始的結果。
關于Router,換一種寫法:
在 app.moudle.ts 文件中,代碼如下 :
imports: [
BrowserModule,
RouterModule.forRoot(
[
{ path: 'home',
component: HomeComponent
},
{
path: 'about',
component: AboutComponent
},
{
path: 'dashboard',
component: DashboardComponent
}
]
)
],這樣一來,可以不用單獨創建 routerConfigure.ts 文件。
小結
自從引入了面向組件(component)后,路由管理相比 AngularJS (1.X),方便了很多。
進一步優化:
或許你已經注意到,當訪問 http://localhost:4200 時,它的路徑應該是 “/”, 我們應該設置這個默認的路徑。
{
path: '',
redirectTo:'/home',
pathMatch: 'full'
},感謝你能夠認真閱讀完這篇文章,希望小編分享的“Angular 5.x之Router怎么用”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。