Angular4.x路由的示例分析-創(chuàng)新互聯(lián)

這篇文章給大家分享的是有關(guān)Angular 4.x路由的示例分析的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。

創(chuàng)新互聯(lián)建站專注于錦江網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗(yàn)。 熱誠(chéng)為您提供錦江營(yíng)銷型網(wǎng)站建設(shè),錦江網(wǎng)站制作、錦江網(wǎng)頁設(shè)計(jì)、錦江網(wǎng)站官網(wǎng)定制、微信小程序開發(fā)服務(wù),打造錦江網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供錦江網(wǎng)站排名全網(wǎng)營(yíng)銷落地服務(wù)。

Installing the router

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

yarn add @angular/router
# OR
npm i --save @angular/router

以上命令執(zhí)行后,將會(huì)自動(dòng)下載@angular/router模塊到node_modules文件夾中。

Base href

我們需要做的最后一件事,是將<base>標(biāo)簽添加到我們的index.html文件中。路由需要根據(jù)這個(gè)來確定應(yīng)用程序的根目錄。例如,當(dāng)我們轉(zhuǎn)到http://example.com/page1時(shí),如果我們沒有定義應(yīng)用程序的基礎(chǔ)路徑,路由將無法知道我們的應(yīng)用的托管地址是http://example.com還是http://example.com/page1。

這件事操作起來很簡(jiǎn)單,只需打開項(xiàng)目中的 index.html 文件,添加相應(yīng)的 <base> 標(biāo)簽,具體如下:

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

以上配置信息告訴 Angular 路由,應(yīng)用程序的根目錄是/。

Using the router

要使用路由,我們需要在AppModule模塊中,導(dǎo)入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 {}

此時(shí)我們的路由還不能正常工作,因?yàn)槲覀冞€未配置應(yīng)用程序路由的相關(guān)信息。RouterModule對(duì)象為我們提供了兩個(gè)靜態(tài)的方法:forRoot()forChild()來配置路由信息。

RouterModule.forRoot()

RouterModule.forRoot() 方法用于在主模塊中定義主要的路由信息,通過調(diào)用該方法使得我們的主模塊可以訪問路由模塊中定義的所有指令。接下來我們來看一下如何使用forRoot()

// ...
import { Routes, RouterModule } from '@angular/router';

export const ROUTES: Routes = [];

@NgModule({
 imports: [
 BrowserModule,
 RouterModule.forRoot(ROUTES)
 ],
 // ...
})
export class AppModule {}

我們通過使用const定義路由的配置信息,然后把它作為參數(shù)調(diào)用RouterModule.forRoot()方法,而不是直接使用RouterModule.forRoot([...])這種方式,這樣做的好處是方便我們?cè)谛枰臅r(shí)候?qū)С?code>ROUTES到其它模塊中。

RouterModule.forChild()

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

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

這個(gè)功能非常強(qiáng)大,因?yàn)槲覀儾槐卦谝粋€(gè)地方(我們的主模塊)定義所有路由信息。反之,我們可以在特性模塊中定義模塊特有的路由信息,并在必要的時(shí)候?qū)⑺鼈儗?dǎo)入我們主模塊。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 {}

通過以上示例,我們知道在主模塊和特性模塊中,路由配置對(duì)象的類型是一樣的,區(qū)別只是主模塊和特性模塊中需調(diào)用不同的方法,來配置模塊路由。接下來我們來介紹一下如何配置ROUTES對(duì)象。

Configuring a route

我們定義的所有路由都是作為ROUTES數(shù)組中的對(duì)象。首先,為我們的主頁定義一個(gè)路由:

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屬性用于定義路由匹配時(shí)需要加載的組件。

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

Displaying routes

配置完路由信息后,下一步是使用一個(gè)名為router-outlet的指令告訴 Angular 在哪里加載組件。當(dāng) Angular 路由匹配到響應(yīng)路徑,并成功找到需要加載的組件時(shí),它將動(dòng)態(tài)創(chuàng)建對(duì)應(yīng)的組件,并將其作為兄弟元素,插入到router-outlet元素中。

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

import { Component } from '@angular/core';

@Component({
 selector: 'app-root',
 template: `
 <div class="app">
  <h4>Our app</h4>
  <router-outlet></router-outlet>
 </div>
 `
})
export class AppComponent {}

我們現(xiàn)在已經(jīng)建立了應(yīng)用程序的主路由,我們可以進(jìn)一步了解路由的其它配置選項(xiàng)。

Further configuration

到目前為止我們已經(jīng)介紹的內(nèi)容只是一個(gè)開始 ,接下來我們來看看其它一些選項(xiàng)和功能。

Dynamic routes

如果路由始終是靜態(tài)的,那沒有多大的用處。例如path: ''是加載我們HomeComponent組件的靜態(tài)路由。我們將介紹動(dòng)態(tài)路由,基于動(dòng)態(tài)路由我們可以根據(jù)不同的路由參數(shù),渲染不同的頁面。

例如,如果我們想要在個(gè)人資料頁面根據(jù)不同的用戶名顯示不同的用戶信息,我們可以使用以下方式定義路由:

import { HomeComponent } from './home/home.component';
import { ProfileComponent } from './profile/profile.component';

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

這里的關(guān)鍵點(diǎn)是:,它告訴 Angular 路由,:username是路由參數(shù),而不是 URL 中實(shí)際的部分。

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

現(xiàn)在我們已經(jīng)建立一個(gè)動(dòng)態(tài)路由,此時(shí)最重要的事情就是如何獲取路由參數(shù)。要訪問當(dāng)前路由的相關(guān)信息,我們需要先從@angular/router模塊中導(dǎo)入ActivatedRoute,然后在組件類的構(gòu)造函數(shù)中注入該對(duì)象,最后通過訂閱該對(duì)象的params屬性,來獲取路由參數(shù),具體示例如下:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

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

介紹完動(dòng)態(tài)路由,我們來探討一下如何創(chuàng)建child routes。

Child routes

實(shí)際上每個(gè)路由都支持子路由,假設(shè)在我們/settings設(shè)置頁面下有/settings/profile/settings/password兩個(gè)頁面,分別表示個(gè)人資料頁和修改密碼頁。

我們可能希望我們的/ settings頁面擁有自己的組件,然后在設(shè)置頁面組件中顯示/ 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 {}

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

接下來,我們需要做的最后一件事是在我們的SettingsComponent組件中添加router-outlet指令,因?yàn)槲覀円谠O(shè)置頁面中呈現(xiàn)子路由。如果我們沒有在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

另一個(gè)很有用的路由功能是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 {}

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

loadChildren

我們也可以告訴路由從另一個(gè)模塊中獲取子路由。這將我們談?wù)摰膬蓚€(gè)想法聯(lián)系在一起 - 我們可以指定另一個(gè)模塊中定義的子路由,以及通過將這些子路由設(shè)置到特定的路徑下,來充分利用component-less路由的功能。

讓我們創(chuàng)建一個(gè)SettingsModule模塊,用來保存所有setttings相關(guān)的路由信息:

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()方法,因?yàn)?code>SettingsModule不是我們應(yīng)用的主模塊。

另一個(gè)主要的區(qū)別是我們將SettingsModule模塊的主路徑設(shè)置為空路徑 ('')。因?yàn)槿绻覀兟窂皆O(shè)置為/settings,它將匹配/settings/settings,很明顯這不是我們想要的結(jié)果。通過指定一個(gè)空的路徑,它就會(huì)匹配/settings路徑,這就是我們想要的結(jié)果。

那么/settings路由信息,需要在哪里配置?答案是在AppModule中。這時(shí)我們就需要用到loadChildren屬性,具體如下:

export const ROUTES: Routes = [
 {
  path: 'settings',
  loadChildren: './settings/settings.module#SettingsModule'
 }
];

@NgModule({
 imports: [
  BrowserModule,
  RouterModule.forRoot(ROUTES)
 ],
 // ...
})
export class AppModule {}

需要注意的是,我們沒有將SettingsModule導(dǎo)入到我們的AppModule中,而是通過loadChildren屬性,告訴 Angular 路由依據(jù)loadChildren屬性配置的路徑去加載SettingsModule模塊。這就是模塊懶加載功能的具體應(yīng)用,當(dāng)用戶訪問/settings/**路徑的時(shí)候,才會(huì)加載對(duì)應(yīng)的SettingsModule模塊,這減少了應(yīng)用啟動(dòng)時(shí)加載資源的大小。

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

  1. 需要導(dǎo)入模塊的相對(duì)路徑

  2. # 分隔符

  3. 導(dǎo)出模塊類的名稱

了解完路由的一些高級(jí)選項(xiàng)和功能,接下來我們來介紹路由指令。

Router Directives

除了router-outlet指令,路由模塊中還提供了一些其它指令。讓我們來看看它們?nèi)绾闻c我們之前介紹的內(nèi)容結(jié)合使用。

routerLink

為了讓我們鏈接到已設(shè)置的路由,我們需要使用routerLink指令,具體示例如下:

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

當(dāng)我們點(diǎn)擊以上的任意鏈接時(shí),頁面不會(huì)被重新加載。反之,我們的路徑將在 URL 地址欄中顯示,隨后進(jìn)行后續(xù)視圖更新,以匹配routerLink中設(shè)置的值。

友情提示:我們也可以將 routerLink 的屬性值,改成數(shù)組形式,以便我們傳遞特定的路由信息

如果我們想要鏈接到動(dòng)態(tài)的路由地址,且該地址有一個(gè)username的路由變量,則我們可以按照以下方式配置routerLink對(duì)應(yīng)的屬性值:

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

routerLinkActive

在實(shí)際開發(fā)中,我們需要讓用戶知道哪個(gè)路由處于激活狀態(tài),通常情況下我們通過向激活的鏈接添加一個(gè) class 來實(shí)現(xiàn)該功能。為了解決上述問題,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指令,當(dāng)a元素對(duì)應(yīng)的路由處于激活狀態(tài)時(shí),active類將會(huì)自動(dòng)添加到a元素上。

最后,我們來簡(jiǎn)單介紹一下 Router API。

Router API

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

import { Component } from '@angular/core';
import { Router } from '@angular/router';

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

組件類中注入的router對(duì)象中有一個(gè)navigate()方法,該方法支持的參數(shù)類型與routerLink指令一樣,當(dāng)調(diào)用該方法后,頁面將會(huì)自動(dòng)跳轉(zhuǎn)到對(duì)應(yīng)的路由地址。具體使用示例如下:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

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

若以上代碼成功運(yùn)行,用戶界面將在 5 秒后被重定向到/settings頁面。這個(gè)方法非常有用,例如當(dāng)檢測(cè)到用戶尚未登錄時(shí),自動(dòng)重定向到登錄頁面。

另一個(gè)使用示例是演示頁面跳轉(zhuǎn)時(shí)如何傳遞數(shù)據(jù),具體如下:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
 selector: 'app-root',
 template: `
  <div class="app">
   <h4>Users</h4>
   <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 路由的功能非常強(qiáng)大,既可以使用指令方式也可以使用命令式 API,希望本文可以幫助你盡快入門,若要進(jìn)一步了解路由詳細(xì)信息,請(qǐng)?jiān)L問 - Angular Router 官文文檔。

我有話說

除了使用navigate()方法外還有沒有其它方法可以實(shí)現(xiàn)頁面導(dǎo)航?

Angular Router API 為我們提供了navigate()navigateByUrl()方法來實(shí)現(xiàn)頁面導(dǎo)航。那為什么會(huì)有兩個(gè)不同的方法呢?

使用router.navigateByUrl()方法與直接改變地址欄上的 URL 地址一樣,我們使用了一個(gè)新的 URL 地址。然而router.navigate()方法基于一系列輸入?yún)?shù),產(chǎn)生一個(gè)新的 URL 地址。為了更好的區(qū)分它們之間的差異,我們來看個(gè)例子,假設(shè)當(dāng)前的 URL 地址是:

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

當(dāng)我們調(diào)用router.navigateByUrl('/inbox/33/message/44')方法后,此時(shí)的 URL 地址將變成/inbox/33/message/44。但如果我們是調(diào)用router.navigate('/inbox/33/message/44')方法,當(dāng)前的 URL 地址將變成/inbox/33/message/44(popup:compose)。

感謝各位的閱讀!關(guān)于“Angular 4.x路由的示例分析”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)建站muchs.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。

網(wǎng)站欄目:Angular4.x路由的示例分析-創(chuàng)新互聯(lián)
鏈接地址:http://muchs.cn/article28/dsoojp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App設(shè)計(jì)品牌網(wǎng)站制作、關(guān)鍵詞優(yōu)化、網(wǎng)站維護(hù)網(wǎng)站改版、軟件開發(fā)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)公司