路由是 Angular 應用程序的核心,它加載與所請求路由相關聯的組件,以及獲取特定路由的相關數據。這允許我們通過控制不同的路由,獲取不同的數據,從而渲染不同的頁面。
接下來我們將按照以下目錄的內容,介紹 Angular 的路由。具體目錄如下:
目錄
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() 方法用于在主模塊中定義主要的路由信息,通過調用該方法使得我們的主模塊可以訪問路由模塊中定義的所有指令。接下來我們來看一下如何使用
新聞熱點
疑難解答
圖片精選