angular2路由预加载

2018-08-20 11:14:48 浏览数 (1)

1. 实现PreloadingStrategy 类

代码语言:javascript复制
import { PreloadingStrategy, Route } from "@angular/router";
import { Observable } from "rxjs";
/**
 * 预加载策略
 */
export class SelectivePreloadingStrategy implements PreloadingStrategy {
    preload(route: Route, load: Function): Observable<any> {
        //当路由中配置data: {preload: true}时预加载
        return route.data && route.data && route.data['preload'] ? load() : Observable.of(null);
    }

}
  • 当你在路由中配置了data: {preload: true}参数后,这里面的策略就返回一个load(),表示需要预加载,如果没有配置就不进行预加载,当然你也可以反过来,默认是预加载,

2.路由添加策略

代码语言:javascript复制
import { NgModule }             from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import {SelectivePreloadingStrategy} from "./selective-preloading-strategy";

import { LoginComponent }      from './login/login.component';
import { MainComponent }   from './main/main.component';



/**
 * app路由
 */
const routes: Routes = [
  { path: '', redirectTo: '/login', pathMatch: 'full' },
  { 
     path: 'login',  
     component: LoginComponent
  },
  { 
     path: 'app',  
     component: MainComponent,
     loadChildren: 'app/main/main.module#MainModule',
     data: {preload: true}
  }
];

export const appRoutes=RouterModule.forRoot(routes,{preloadingStrategy: SelectivePreloadingStrategy});

3.AppModule中providers添加

代码语言:javascript复制
/**
 * app模块
 */
@NgModule({
  imports: [
    appRoutes,
    BrowserModule,
    BrowserAnimationsModule,
    NgbModule.forRoot(),
    MainModule,
    LoginModule
  ],
  declarations: [
    AppComponent,
    ToastBoxComponent,
    ToastComponent,
    SpinComponent
  ],
  providers: [AppService,ToastService,HttpService,SpinService,SelectivePreloadingStrategy],
  exports:[ToastBoxComponent,SpinComponent],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

4.路由使用

代码语言:javascript复制
import { NgModule, OnInit } from '@angular/core';
import { RouterModule, Routes, Router } from '@angular/router';

/**
 * 主体路由
 */
const routes: Routes = [
      { path: 'home', loadChildren: 'app/home/home.module#HomeModule', data: {preload: true} },
      { path: 'demo', loadChildren: 'app/demo/demo.module#DemoModule', data: {preload: true} },
];

export const mainRoutes = RouterModule.forChild(routes);

0 人点赞