Angular9 定義基本路由

2020-07-06 16:29 更新

創(chuàng)建路由有三個基本的構(gòu)建塊。

AppRoutingModule 導(dǎo)入 AppModule 并把它添加到 imports 數(shù)組中。

Angular CLI 會為你執(zhí)行這一步驟。但是,如果要手動創(chuàng)建應(yīng)用或使用現(xiàn)存的非 CLI 應(yīng)用,請驗證導(dǎo)入和配置是否正確。下面是使用 --routing 標(biāo)志生成的默認(rèn) AppModule。

//Default CLI AppModule with routing


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module'; // CLI imports AppRoutingModule
import { AppComponent } from './app.component';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule // CLI adds AppRoutingModule to the AppModule's imports array
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

  1. RouterModuleRoutes 導(dǎo)入到你的路由模塊中。

Angular CLI 會自動執(zhí)行這一步驟。CLI 還為你的路由設(shè)置了 Routes 數(shù)組,并為 @NgModule() 配置了 importsexports 數(shù)組。

    //CLI app routing module


    import { NgModule } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router'; // CLI imports router


    const routes: Routes = []; // sets up routes constant where you define your routes


    // configures NgModule imports and exports
    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule]
    })
    export class AppRoutingModule { }

  1. Routes 數(shù)組中定義你的路由。

這個數(shù)組中的每個路由都是一個包含兩個屬性的 JavaScript 對象。第一個屬性 path 定義了該路由的 URL 路徑。第二個屬性 component 定義了要讓 Angular 用作相應(yīng)路徑的組件。

    //AppRoutingModule (excerpt)


    const routes: Routes = [
      { path: 'first-component', component: FirstComponent },
      { path: 'second-component', component: SecondComponent },
    ];

  1. 把這些路由添加到你的應(yīng)用中。

現(xiàn)在你已經(jīng)定義了路由,可以把它們添加到應(yīng)用中了。首先,添加到這兩個組件的鏈接。把要添加路由的鏈接賦值給 routerLink 屬性。將屬性的值設(shè)置為該組件,以便在用戶點擊各個鏈接時顯示這個值。接下來,修改組件模板以包含 <router-outlet> 標(biāo)簽。該元素會通知 Angular,你可以用所選路由的組件更新應(yīng)用的視圖。

    //Template with routerLink and router-outlet


    <h1>Angular Router App</h1>
    <!-- This nav gives you links to click, which tells the router which route to use (defined in the routes constant in  AppRoutingModule) -->
    <nav>
      <ul>
        <li><a routerLink="/first-component" routerLinkActive="active">First Component</a></li>
        <li><a routerLink="/second-component" routerLinkActive="active">Second Component</a></li>
      </ul>
    </nav>
    <!-- The routed views render in the <router-outlet>-->
    <router-outlet></router-outlet>

路由順序

路由的順序很重要,因為 Router 在匹配路由時使用“先到先得”策略,所以應(yīng)該在不那么具體的路由前面放置更具體的路由。首先列出靜態(tài)路徑的路由,然后是一個與默認(rèn)路由匹配的空路徑路由。通配符路由是最后一個,因為它匹配每一個 URL,只有當(dāng)其它路由都沒有匹配時,Router 才會選擇它。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號