當(dāng)項(xiàng)目變得復(fù)雜龐大以后,如果所有頁(yè)面都在一個(gè)模塊里,就會(huì)出現(xiàn)首頁(yè)加載慢的問題,因?yàn)槭醉?yè)就已經(jīng)把整個(gè)項(xiàng)目加載進(jìn)來了。所以,很有必要根據(jù)業(yè)務(wù)將不同的功能分模塊,以便Angular2按需加載,提升用戶體驗(yàn)。
下面的例子是將首頁(yè)放到home模塊里,訪問/home時(shí)加載home模塊內(nèi)容,僅供學(xué)習(xí)懶加載,其實(shí)首頁(yè)訪問路徑應(yīng)該是/
先看項(xiàng)目文件結(jié)構(gòu):
home模塊放到src/app/home目錄下,里面的home目錄是home組件。
home模塊有單獨(dú)的定義和路由(home.module.ts,home-routing.module.ts)
創(chuàng)建HOME模塊和HOME組件:
cd src/app/ mkdir home cd home ng g module home ng g component home
創(chuàng)建HOME模塊的路由配置模塊
創(chuàng)建 home-routing.module.ts:
import {Routes, RouterModule} from "@angular/router"; import {HomeComponent} from "./home/home.component"; import {NgModule} from "@angular/core"; const routes: Routes=[ { path:'', component:HomeComponent } ] @NgModule({ imports:[RouterModule.forChild(routes)], exports:[RouterModule], providers:[] }) export class HomeRoutingModule{}
模塊下的頁(yè)面都可以單獨(dú)在該模塊自己的的路由配置模塊上配置,而不用在app-routing.module.ts里配置,注意RouterModule.forChild(routes)
home.module.ts導(dǎo)入路由模塊:
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HomeComponent } from './home/home.component'; import {HomeRoutingModule} from "./home-routing.module"; @NgModule({ imports: [ CommonModule, HomeRoutingModule ], declarations: [HomeComponent] }) export class HomeModule { }
在app-routing.module.ts配置路由:
import {NgModule} from "@angular/core"; import {Routes, RouterModule} from "@angular/router"; import {UserListComponent} from "./user/user-list/user-list.component"; import {UserDetailComponent} from "./user/user-detail/user-detail.component"; import {RxjsComponent} from "./rxjs/rxjs.component"; import {UserEditComponent} from "./user/user-edit/user-edit.component"; import {environment} from "../environments/environment"; const routes: Routes = [ { path:'home', loadChildren:'app/home/home.module#HomeModule' } ]; @NgModule({ imports: [RouterModule.forRoot(routes,{ useHash: environment.useHash })], exports: [RouterModule], providers: [] }) export class AppRoutingModule { }
配置home路徑,使用loadChildren加載home模塊
完成后打開chrome的開發(fā)者工具,切到Network,看看不同的頁(yè)面是不是加載了不同的文件。
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com