Angular应用内路由(In App Route)的最佳实践
Angular官網(wǎng)里關(guān)于路由開發(fā)的最佳實踐指導(dǎo):
In Angular, the best practice is to load and configure the router in a separate, top-level module that is dedicated to routing and imported by the root AppModule.
By convention, the module class name is AppRoutingModule and it belongs in the app-routing.module.ts in the src/app folder.
使用命令行生成路由module:
ng generate module app-routing --flat --module=app
flat的含義: 把生成的module放到項目根目錄下面,而不是放到一個單獨目錄下。
–module=app:告訴CLI該module生成完畢后,注冊到AppModule的imports數(shù)組內(nèi)。
代碼如下:
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HeroesComponent } from './heroes/heroes.component';const routes: Routes = [{ path: 'heroes', component: HeroesComponent } ];@NgModule({imports: [RouterModule.forRoot(routes)],exports: [RouterModule] }) export class AppRoutingModule { }Routes告訴Router,當(dāng)用戶點擊了url或者將路徑粘貼到地址欄之后,應(yīng)該打開哪個視圖。
RouterModule.forRoot(routes)方法的作用:
configure the router at the application’s root level. The forRoot() method supplies the service providers and directives needed for routing, and performs the initial navigation based on the current browser URL.
使用route之前的app Component html:
使用route之后:
<h1>{{title}}</h1> <router-outlet></router-outlet> <app-messages></app-messages>The tells the router where to display routed views: 告訴router在哪里顯示被路由器控制的視圖。
RouterOutle是router指令,整個AppComponent范圍內(nèi)都可用,因為在AppModule里導(dǎo)入了AppRoutingModule,而后者又export了RouterModule.
測試:
要獲取更多Jerry的原創(chuàng)文章,請關(guān)注公眾號"汪子熙":
總結(jié)
以上是生活随笔為你收集整理的Angular应用内路由(In App Route)的最佳实践的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 马斯克疯狂降价!特斯拉Model Y已比
- 下一篇: 英特尔 GPU 部门新老大 Deepak