1. 程式人生 > >Angular 中使用惰性加載

Angular 中使用惰性加載

gpo ade ports 初始 mon div 告訴 exp 大小

一些模塊使用延遲加載後,只有當用戶第一次導航到這個模塊時,才會加載一些特性。這對於應用程序的性能和減小初始包的大小有很大的幫助。另外,設置非常簡單。

延遲加載的路由需要在根應用程序模塊之外,所以需要將惰性加載特性假如特性模塊中。

$ ng g module shop
$ ng g c shop/cart
$ ng g c shop/checkout
$ ng g c shop/confirm

在主路由配置中,需要執行以下操作:

import { Routes } from ‘@angular/router‘;

// BoutiqueComponent is a normal, eager loaded component
import { BoutiqueComponent } from ‘./boutique/boutique.component‘; export const routes: Routes = [ { path: ‘‘, component: BoutiqueComponent, pathMatch: ‘full‘ }, { path: ‘shop‘, loadChildren: ‘./shop/shop.module#ShopModule‘ }, { path: ‘**‘, component: BoutiqueComponent } ];

上面使用了loadChildren,首先他通往模塊的路徑,然後#後面跟的是模塊的類名。它指示路由器,模塊應該是惰性加載,並告訴它在哪裏找到模塊。

剩下要做的就是配置特定於功能模塊的路由:

import { Routes } from ‘@angular/router‘;

import { CartComponent } from ‘./cart/cart.component‘;
import { CheckoutComponent } from ‘./checkout/checkout.component‘;
import { ConfirmComponent } from ‘./confirm/confirm.component‘;

export const routes: Routes = [
    { path: ‘‘, component: CartComponent },
    { path: 
‘checkout‘, component: CheckoutComponent }, { path: ‘confirm‘, component: ConfirmComponent }, ];

最後,在惰性模塊中,使用RouterModule中得forChild替換forRoot。

import { NgModule } from ‘@angular/core‘;
import { CommonModule } from ‘@angular/common‘;

import { CartComponent } from ‘./cart/cart.component‘;
import { CheckoutComponent } from ‘./checkout/checkout.component‘;
import { ConfirmComponent } from ‘./confirm/confirm.component‘;

import { routes } from ‘./shop.routing‘;
import { RouterModule } from ‘@angular/router‘;


@NgModule({
  imports: [
    RouterModule.forChild(routes)
  ],
  declarations: [CartComponent, CheckoutComponent, ConfirmComponent]
})
export class LegalModule { }

這就是它得全部。現在訪問/shop,/shop/checkout這些模塊將在第一次加載這些路徑時加載。tip:假如不能立即生效,可以重啟下sever。

惰性加載的一些問題可以在模塊問題裏找到。

Angular 中使用惰性加載