ng2路由延时加载模块

1、 app.module.ts

import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {HttpModule} from '@angular/http';
import {RouterModule, Routes} from "@angular/router";
import {AppComponent} from './components/app.component';
import {HomeComponent} from "./components/home.component";
import {ContactComponent} from "./components/contact.component";
// 这样就实现了延时加载
// 我们使用属性loadChildren而不是component 。
// 我们传递一个字符串而不是一个符号,以避免加载模块。
// 我们不仅定义了模块的路径,还定义了类的名称。
const MyRouter:Routes = [
  {
    path: "home",
    component: HomeComponent
  },
  {
    path: "about",
    loadChildren: "app/about.module#AboutModule"
  },
  {
    path: "contact",
    component: ContactComponent
  },
  {
    path: "**",
    redirectTo: "home"
  }
];

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    ContactComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot(MyRouter)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {
}

2、app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: '../templates/app.component.html'
})
export class AppComponent {
  
}

3、app.component.html

首页
联系我们
关于我们
我们列表

4、home.component.ts

import {Component} from "@angular/core";
@Component({
  selector: "my-home",
  template: "首页"
})
export class HomeComponent {
  constructor() {
    console.log("home");
  }
}

5、about.module.ts

import {NgModule} from '@angular/core';
import {RouterModule, Routes} from "@angular/router";
import {AboutComponent} from "./components/about.component";
import {ListComponent} from "./components/list.component";

const childRouter:Routes = [
  {
    path: '',
    component: AboutComponent
  },
  {
    path: "list",
    component: ListComponent
  }
];
@NgModule({
  imports: [
    RouterModule.forChild(childRouter)
  ],
  declarations: [
    AboutComponent,
    ListComponent
  ]
})
export class AboutModule {

}

6、about.component.ts

import {Component, OnInit} from "@angular/core";
@Component({
  selector: "my-about",
  template: "关于我们"
})
export class AboutComponent {
  constructor() {
    console.log("about");
  }
}

7、list.component.ts

import {Component} from "@angular/core";
@Component({
  selector: "my-list",
  template: "列表"
})
export class ListComponent {
  constructor() {
    console.log("list");
  }
}

你可能感兴趣的:(路由,router,延时,angular2)