Angular 4.x 路由快速入門學習,angular4.x

來源:互聯網
上載者:User

Angular 4.x 路由快速入門學習,angular4.x

路由是 Angular 應用程式的核心,它載入與所請求路由相關聯的組件,以及擷取特定路由的相關資料。這允許我們通過控制不同的路由,擷取不同的資料,從而渲染不同的頁面。

接下來我們將按照以下目錄的內容,介紹 Angular 的路由。具體目錄如下:

目錄

  1. Installing the router
    1. Base href
  2. Using the router
    1. RouterModule.forRoot
    2. RouterModule.forChild
  3. Configuring a route
  4. Displaying routes
  5. Futher configuration
    1. Dynamic routes
    2. Child routes
    3. Component-less routes
    4. loadChildren
  6. Router directives
    1. routerLink
    2. routerLinkActive
  7. Router API

Installing the router

首先第一件事,我們需要安裝 Angular Router。你可以通過運行以下任一操作來執行此操作:

yarn add @angular/router# ORnpm i --save @angular/router

以上命令執行後,將會自動下載 @angular/router 模組到 node_modules 檔案夾中。

Base href

我們需要做的最後一件事,是將 <base> 標籤添加到我們的 index.html 檔案中。路由需要根據這個來確定應用程式的根目錄。例如,當我們轉到 http://example.com/page1 時,如果我們沒有定義應用程式的基礎路徑,路由將無法知道我們的應用的託管地址是 http://example.com 還是 http://example.com/page1

這件事操作起來很簡單,只需開啟項目中的 index.html 檔案,添加相應的 <base> 標籤,具體如下:

<!doctype html><html> <head> <base href="/" rel="external nofollow" > <title>Application</title> </head> <body> <app-root></app-root> </body></html>

以上配置資訊告訴 Angular 路由,應用程式的根目錄是 /

Using the router

要使用路由,我們需要在 AppModule 模組中,匯入 RouterModule 。具體如下:

import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { RouterModule } from '@angular/router';import { AppComponent } from './app.component';@NgModule({ imports: [ BrowserModule, RouterModule ], bootstrap: [ AppComponent ], declarations: [ AppComponent ]})export class AppModule {}

此時我們的路由還不能正常工作,因為我們還未配置應用程式路由的相關資訊。RouterModule 對象為我們提供了兩個靜態方法:forRoot() forChild() 來配置路由資訊。

RouterModule.forRoot()

RouterModule.forRoot() 方法用於在主模組中定義主要的路由資訊,通過調用該方法使得我們的主模組可以訪問路由模組中定義的所有指令。接下來我們來看一下如何使用 forRoot()

// ...import { Routes, RouterModule } from '@angular/router';export const ROUTES: Routes = [];@NgModule({ imports: [ BrowserModule, RouterModule.forRoot(ROUTES) ], // ...})export class AppModule {}

我們通過使用 const 定義路由的配置資訊,然後把它作為參數調用 RouterModule.forRoot() 方法,而不是直接使用 RouterModule.forRoot([...]) 這種方式,這樣做的好處是方便我們在需要的時候匯出 ROUTES 到其它模組中。

RouterModule.forChild()

RouterModule.forChild() 與 Router.forRoot() 方法類似,但它只能應用在特性模組中。

友情提示:根模組中使用 forRoot(),子模組中使用 forChild()

這個功能非常強大,因為我們不必在一個地方(我們的主模組)定義所有路由資訊。反之,我們可以在特性模組中定義模組特有的路由資訊,並在必要的時候將它們匯入我們主模組。RouterModule.forChild() 的使用方法如下:

import { NgModule } from '@angular/core';import { CommonModule } from '@angular/common';import { Routes, RouterModule } from '@angular/router';export const ROUTES: Routes = [];@NgModule({ imports: [ CommonModule, RouterModule.forChild(ROUTES) ], // ...})export class ChildModule {}

通過以上樣本,我們知道在主模組和特性模組中,路由設定物件的類型是一樣的,區別只是主模組和特性模組中需調用不同的方法,來配置模組路由。接下來我們來介紹一下如何配置 ROUTES 對象。

Configuring a route

我們定義的所有路由都是作為 ROUTES 數組中的對象。首先,為我們的首頁定義一個路由:

import { Routes, RouterModule } from '@angular/router';import { HomeComponent } from './home/home.component';export const ROUTES: Routes = [ { path: '', component: HomeComponent }];@NgModule({ imports: [ BrowserModule, RouterModule.forRoot(ROUTES) ], // ...})export class AppModule {}

樣本中我們通過 path 屬性定義路由的匹配路徑,而 component 屬性用於定義路由匹配時需要載入的組件。

友情提示:我們使用 path: '' 來匹配空的路徑,例如:https://yourdomain.com

Displaying routes

配置完路由資訊後,下一步是使用一個名為 router-outlet 的指令告訴 Angular 在哪裡載入組件。當 Angular 路由匹配到響應路徑,並成功找到需要載入的組件時,它將動態建立對應的組件,並將其作為兄弟元素,插入到 router-outlet 元素中。

在我們 AppComponent 組件中,我們可以在任意位置插入 router-outlet 指令:

import { Component } from '@angular/core';@Component({ selector: 'app-root', template: ` <div class="app">  <h3>Our app</h3>  <router-outlet></router-outlet> </div> `})export class AppComponent {}

我們現在已經建立了應用程式的主路由,我們可以進一步瞭解路由的其它配置選項。

Further configuration

到目前為止我們已經介紹的內容只是一個開始 ,接下來我們來看看其它一些選項和功能。

Dynamic routes

如果路由始終是靜態,那沒有多大的用處。例如 path: '' 是載入我們 HomeComponent 組件的靜態路由。我們將介紹動態路由,基於動態路由我們可以根據不同的路由參數,渲染不同的頁面。

例如,如果我們想要在設定檔頁面根據不同的使用者名稱顯示不同的使用者資訊,我們可以使用以下方式定義路由:

import { HomeComponent } from './home/home.component';import { ProfileComponent } from './profile/profile.component';export const ROUTES: Routes = [ { path: '', component: HomeComponent }, { path: '/profile/:username', component: ProfileComponent }];

這裡的關鍵點是 : ,它告訴 Angular 路由,:username 是路由參數,而不是 URL 中實際的部分。

友情提示:如果沒有使用 : ,它將作為靜態路由,僅匹配 /profile/username 路徑

現在我們已經建立一個動態路由,此時最重要的事情就是如何擷取路由參數。要訪問當前路由的相關資訊,我們需要先從 @angular/router 模組中匯入 ActivatedRoute ,然後在組件類的建構函式中注入該對象,最後通過訂閱該對象的 params 屬性,來擷取路由參數,具體樣本如下:

import { Component, OnInit } from '@angular/core';import { ActivatedRoute } from '@angular/router';@Component({ selector: 'profile-page', template: ` <div class="profile">  <h3>{{ username }}</h3> </div> `})export class SettingsComponent implements OnInit { username: string; constructor(private route: ActivatedRoute) {} ngOnInit() { this.route.params.subscribe((params) => this.username = params.username); }}

介紹完動態路由,我們來探討一下如何建立 child routes

Child routes

實際上每個路由都支援子路由,假設在我們 /settings 設定頁面下有 /settings/profile /settings/password 兩個頁面,分別表示設定檔頁和修改密碼頁。

我們可能希望我們的 / settings 頁面擁有自己的組件,然後在設定頁面組件中顯示 / settings/profile / settings/password 頁面。我們可以這樣做:

import { SettingsComponent } from './settings/settings.component';import { ProfileSettingsComponent } from './settings/profile/profile.component';import { PasswordSettingsComponent } from './settings/password/password.component';export const ROUTES: Routes = [ {   path: 'settings',   component: SettingsComponent,  children: [   { path: 'profile', component: ProfileSettingsComponent },   { path: 'password', component: PasswordSettingsComponent }  ] }];@NgModule({ imports: [  BrowserModule,  RouterModule.forRoot(ROUTES) ],})export class AppModule {}

在這裡,我們在 setttings 路由中定義了兩個子路由,它們將繼承父路由的路徑,因此修改密碼頁面的路由匹配地址是 /settings/password ,依此類推。

接下來,我們需要做的最後一件事是在我們的 SettingsComponent 組件中添加 router-outlet 指令,因為我們要在設定頁面中呈現子路由。如果我們沒有在 SettingsComponent 組件中添加 router-outlet 指令,儘管 /settings/password 匹配修改密碼頁面的路由地址,但修改密碼頁面將無法正常顯示。具體代碼如下:

import { Component } from '@angular/core';@Component({ selector: 'settings-page', template: `  <div class="settings">   <settings-header></settings-header>   <settings-sidebar></settings-sidebar>   <router-outlet></router-outlet>  </div> `})export class SettingsComponent {}

Component-less routes

另一個很有用的路由功能是 component-less 路由。使用 component-less 路由允許我們將路由群組合在一起,並讓它們共用路由配置資訊和 outlet。

例如,我們可以定義 setttings 路由而不需要使用 SettingsComponent 組件:

import { ProfileSettingsComponent } from './settings/profile/profile.component';import { PasswordSettingsComponent } from './settings/password/password.component';export const ROUTES: Routes = [ {  path: 'settings',  children: [   { path: 'profile', component: ProfileSettingsComponent },   { path: 'password', component: PasswordSettingsComponent }  ] }];@NgModule({ imports: [  BrowserModule,  RouterModule.forRoot(ROUTES) ],})export class AppModule {}

此時, /settings/profile /settings/password 路由定義的內容,將顯示在 AppComponent 組件的 router-outlet 元素中。

loadChildren

我們也可以告訴路由從另一個模組中擷取子路由。這將我們談論的兩個想法聯絡在一起 - 我們可以指定另一個模組中定義的子路由,以及通過將這些子路由設定到特定的路徑下,來充分利用 component-less 路由的功能。

讓我們建立一個 SettingsModule 模組,用來儲存所有 setttings 相關的路由資訊:

import { NgModule } from '@angular/core';import { CommonModule } from '@angular/common';import { Routes, RouterModule } from '@angular/router';export const ROUTES: Routes = [ {  path: '',  component: SettingsComponent,  children: [   { path: 'profile', component: ProfileSettingsComponent },   { path: 'password', component: PasswordSettingsComponent }  ] }];@NgModule({ imports: [  CommonModule,  RouterModule.forChild(ROUTES) ],})export class SettingsModule {}

需要注意的是,在 SettingsModule 模組中我們使用 forChild() 方法,因為 SettingsModule 不是我們應用的主模組。

另一個主要的區別是我們將 SettingsModule 模組的主路徑設定為空白路徑 ('')。因為如果我們路徑設定為 /settings ,它將匹配 /settings/settings ,很明顯這不是我們想要的結果。通過指定一個空的路徑,它就會匹配 /settings 路徑,這就是我們想要的結果。

那麼 /settings 路由資訊,需要在哪裡配置?答案是在 AppModule 中。這時我們就需要用到 loadChildren 屬性,具體如下:

export const ROUTES: Routes = [ {  path: 'settings',  loadChildren: './settings/settings.module#SettingsModule' }];@NgModule({ imports: [  BrowserModule,  RouterModule.forRoot(ROUTES) ], // ...})export class AppModule {}

需要注意的是,我們沒有將 SettingsModule 匯入到我們的 AppModule 中,而是通過 loadChildren 屬性,告訴 Angular 路由依據 loadChildren 屬性配置的路徑去載入 SettingsModule 模組。這就是模組懶載入功能的具體應用,當使用者訪問 /settings/** 路徑的時候,才會載入對應的 SettingsModule 模組,這減少了應用啟動時載入資源的大小。

另外我們傳遞一個字串作為 loadChildren 的屬性值,該字串由三部分組成:

  1. 需要匯入模組的相對路徑
  2. # 分隔字元
  3. 匯出模組類的名稱

瞭解完路由的一些進階選項和功能,接下來我們來介紹路由指令。

Router Directives

除了 router-outlet 指令,路由模組中還提供了一些其它指令。讓我們來看看它們如何與我們之前介紹的內容結合使用。

routerLink

為了讓我們連結到已設定的路由,我們需要使用 routerLink 指令,具體樣本如下:

<nav> <a routerLink="/">Home</a> <a routerLink="/settings/password">Change password</a> <a routerLink="/settings/profile">Profile Settings</a></nav>

當我們點擊以上的任意連結時,頁面不會被重新載入。反之,我們的路徑將在 URL 地址欄中顯示,隨後進行後續視圖更新,以匹配 routerLink 中設定的值。

友情提示:我們也可以將 routerLink 的屬性值,改成數組形式,以便我們傳遞特定的路由資訊

如果我們想要連結到動態路由地址,且該地址有一個 username 的路由變數,則我們可以按照以下方式配置 routerLink 對應的屬性值:

<a [routerLink]="['/profile', username]"> Go to {{ username }}'s profile.</a>

routerLinkActive

在實際開發中,我們需要讓使用者知道哪個路由處於啟用狀態,通常情況下我們通過向啟用的連結添加一個 class 來實現該功能。為瞭解決上述問題,Angular 路由模組為我們提供了 routerLinkActive 指令,該指令的使用樣本如下:

<nav> <a routerLink="/settings" routerLinkActive="active">Home</a> <a routerLink="/settings/password" routerLinkActive="active">Change password</a> <a routerLink="/settings/profile" routerLinkActive="active">Profile Settings</a></nav>

通過使用 routerLinkActive 指令,當 a 元素對應的路由處於啟用狀態時,active 類將會自動添加到 a 元素上。

最後,我們來簡單介紹一下 Router API。

Router API

我們可以通過路由還提供的 API 實現與 routerLink 相同的功能。要使用 Router API,我們需要在組件類中注入 Router 對象,具體如下:

import { Component } from '@angular/core';import { Router } from '@angular/router';@Component({ selector: 'app-root', template: `  <div class="app">   <h3>Our app</h3>   <router-outlet></router-outlet>  </div> `})export class AppComponent { constructor(private router: Router) {}}

組件類中注入的 router 對象中有一個 navigate() 方法,該方法支援的參數類型與 routerLink 指令一樣,當調用該方法後,頁面將會自動跳轉到對應的路由地址。具體使用樣本如下:

import { Component, OnInit } from '@angular/core';import { Router } from '@angular/router';@Component({ selector: 'app-root', template: `  <div class="app">   <h3>Our app</h3>   <router-outlet></router-outlet>  </div> `})export class AppComponent implements OnInit { constructor(private router: Router) {} ngOnInit() {  setTimeout(() => {   this.router.navigate(['/settings']);  }, 5000); }}

若以上代碼成功運行,使用者介面將在 5 秒後被重新導向到 /settings 頁面。這個方法非常有用,例如當檢測到使用者尚未登入時,自動重新導向到登入頁面。

另一個使用樣本是示範頁面跳轉時如何傳遞資料,具體如下:

import { Component, OnInit } from '@angular/core';import { Router } from '@angular/router';@Component({ selector: 'app-root', template: `  <div class="app">   <h3>Users</h3>   <div *ngFor="let user of users">    <user-component      [user]="user"     (select)="handleSelect($event)">    </user-component>   </div>   <router-outlet></router-outlet>  </div> `})export class AppComponent implements OnInit { users: Username[] = [  { name: 'toddmotto', id: 0 },  { name: 'travisbarker', id: 1 },  { name: 'tomdelonge', id: 2 } ];  constructor(private router: Router) {}  handleSelect(event) {  this.router.navigate(['/profile', event.name]); }}

Angular 路由的功能非常強大,既可以使用指令方式也可以使用命令式 API,希望本文可以協助你儘快入門,若要進一步瞭解路由詳細資料,請訪問 - Angular Router 官文文檔。

我有話說

除了使用 navigate() 方法外還有沒有其它方法可以實現頁面導航?

Angular Router API 為我們提供了 navigate() navigateByUrl() 方法來實現頁面導航。那為什麼會有兩個不同的方法呢?

使用 router.navigateByUrl() 方法與直接改變地址欄上的 URL 地址一樣,我們使用了一個新的 URL 地址。然而 router.navigate() 方法基於一系列輸入參數,產生一個新的 URL 地址。為了更好的區分它們之間的差異,我們來看個例子,假設當前的 URL 地址是:

/inbox/11/message/22(popup:compose)

當我們調用 router.navigateByUrl('/inbox/33/message/44') 方法後,此時的 URL 地址將變成 /inbox/33/message/44 。但如果我們是調用 router.navigate('/inbox/33/message/44') 方法,當前的 URL 地址將變成 /inbox/33/message/44(popup:compose)

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.