angular2路由预加载

1. 实现PreloadingStrategy 类


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.路由添加策略


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添加


/**
 * 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.路由使用


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);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,670评论 19 139
  • 导航是很简单的,只是不同页面之间的切换,路由是实现导航的一种。 一个url对应的一个页面,在angular2中是一...
    贺贺v5阅读 8,186评论 5 9
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,093评论 6 342
  • 一:路由基础 什么是路由: 在web开发中,路由的概念由来已久,简而言之,就是利用URL的唯一性来指定特定的事物,...
    真的稻城阅读 11,203评论 2 7
  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 11,164评论 0 4