zoukankan      html  css  js  c++  java
  • [Angular2 Router] Lazy Load Angular 2 Modules with the Router

    Angular 2 lazy loading is a core feature of Angular 2. Lazy loading allows your application to start up faster because it only needs to use the main App Module when the page initially loads. As you navigate between routes, it will load the additional modules as you define them in your routes. Make sure to properly organize your files into Angular 2’s module pattern so that files that belong to each module don’t get required by other modules.

    First we need to arrange the component into different module.

    Create Four files 

    • home.module.ts
    • home.routes.ts
    • contact.module.ts
    • contact.routes.ts

    Each modue.ts will the entery file for this module, Angualr2 lazy loads the module in by router.


    import {RouterModule} from "@angular/router";
    const routes = [
      {path: '', loadChildren: 'app/home/home.module'},
      {path: 'contact', loadChildren: 'app/contact/contact.module'},
    export default RouterModule.forRoot(routes);

    Here we use 'loadChildren' instead of 'component'. This helps lazy loading, to deduce the bundle size.

    Also we point to the location of the module file for each component.

    'forRoot': because app.routes.ts is the main entery point, for each child module, we will use 'forChild'


    import {HomeComponent} from "./home.component";
    import {RouterModule} from "@angular/router";
    const routes = [
      {path: '', component: HomeComponent}
    export default RouterModule.forChild(routes);


    import {NgModule} from "@angular/core";
    import {CommonModule} from "@angular/common";
    import {HomeComponent} from "./home.component";
    import {SearchBarComponent} from "./search-bar/search-bar.component";
    import {ResultListComponent} from "./result-list/result-list.component";
    import homeRoutes from './home.routes';
      imports: [
      declarations: [HomeComponent, SearchBarComponent, ResultListComponent],
      exports: [HomeComponent, SearchBarComponent, ResultListComponent]
    export default class HomeModule{}

    In module file, we import routes. 

    The same partten for contact component. To prove that, when we click the contact routeLink, we can see from the Devtool Netwrok panel, it load the contact module:


  • 相关阅读:
    Leetcode[33]-Search in Rotated Sorted Array
    JSON格式的时间“/Date(1530104033000)/”格式转为正常的年-月-日 格式的代码
    echart 图例设置自定义图标?
    easyui datagrid实现拖动表头
    ASP.NET MVC提交LIST列表到后台接收不到数据
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5906995.html
Copyright © 2011-2022 走看看