Home >Web Front-end >JS Tutorial >A brief discussion on preloading configuration and lazy loading configuration in Angular
This article will take you to understand the routing configuration in Angular, and briefly introduce the preloading configuration and lazy loading configuration. I hope it will be helpful to everyone!
NgModule is the core of the Angular module. Let’s talk about it first.
1. The role of @NgModule:
2. @NgModule structure description:
@NgModule({ declarations: [], //属于当前模块的组件、指令及管道 imports: [], //当前模板所依赖的项,即外部模块(包括httpModule、路由等) export:[],//声明出应用给其他的module使用 providers: [], //注入服务到当前模块 bootstrap: []//默认启动哪个组件(只有根模块才能设置bootstrap属性) })
3. Lazy loading instructions
(1) The RouterModule
object provides two static methods: forRoot ()
and forChild()
to configure routing information.
forRoot()//Define the main routing information in the main module
forChild()``//
Application in feature module (sub-module)(2) Lazy loading: loadChildren
The corresponding module is not added to AppModule here , but through the loadChildren
attribute, tell Angular routing to load the corresponding module based on the path configured with the loadChildren
attribute. This is the specific application of the module lazy loading function. When the user accesses the /xxx/** path, the corresponding module will be loaded, which reduces the size of the resources loaded when the application starts. The attribute value of loadChildren consists of three parts:
(3) Preloading
When lazy loading is used, the response is sometimes delayed when the route loads a module for the first time. At this time, you can use the preloading strategy to solve this problem.
Angular provides two loading strategies,
PreloadAllModules
-preloadingNoPreloading
-no preloading (default). RouterModule.forRoo()
The second parameter can add configuration options, one of the configuration options is
preloadingStrategy Configuration, this configuration is a preload policy configuration.
//使用默认预加载-预加载全部模块 import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { routes } from './main.routing'; import { RouterModule } from '@angular/router'; import { PreloadAllModules } from '@angular/router'; @NgModule({ declarations: [AppComponent], imports: [ BrowserModule, RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules }) ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }However, we prefer to control the preloading of modules ourselves. In this case, we need to customize the preloading strategyA. Customize - load all modules after 5 seconds
Create a new custom-preloading-strategy.ts file at the same level as the app.
import { Route } from '@angular/router'; import { PreloadingStrategy } from '@angular/router'; import { Observable } from 'rxjs/Rx'; export class CustomPreloadingStrategy implements PreloadingStrategy { preload(route: Route, fn: () => Observable<boolean>): Observable<boolean> { return Observable.of(true).delay(5000).flatMap((_: boolean) => fn()); } }Inject
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { HomeComponent } from './home/home.component'; import { routes } from './main.routing'; import { RouterModule } from '@angular/router'; import { CustomPreloadingStrategy } from './preload'; @NgModule({ declarations: [ AppComponent, HomeComponent ], imports: [ BrowserModule, RouterModule.forRoot(routes, { preloadingStrategy: CustomPreloadingStrategy }) ], providers: [CustomPreloadingStrategy ], bootstrap: [AppComponent] }) export class AppModule { }B, custom-specified module into the providers of app.modules.ts PreloadingCreate a selective-preloading-strategy.ts file at the same level as the app (it needs to be injected by providers in app-routing.module.ts, and then the data defined in the route is passed through additional parameters) Set whether to preload)
import { Injectable } from '@angular/core'; import { PreloadingStrategy, Route } from '@angular/router'; import { Observable} from 'rxjs/Observable'; import 'rxjs/add/observable/of'; @Injectable() export class SelectivePreloadingStrategy implements PreloadingStrategy { preloadedModules: string[] = []; preload(route: Route, load: () => Observable<any>): Observable<any> { if (route.data && route.data['preload']) { return load(); } else { return Observable.of(null); } } }app-routing.module.ts (This file combines lazy loading with preloading)
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { CanDeactivateGuard } from './guard/can-deactivate-guard.service'; import { SelectivePreloadingStrategy } from './selective-preloading-strategy'; // 预加载 import { PageNotFoundComponent } from './not-found.component'; const appRoutes: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'full'}, { path: 'mian', loadChildren: './main/mian.module#MainModule' }, // 懒加载(在这个层级的router配置文件及module文件都不需要引入该组建) { path: 'home', loadChildren: './home/home.module#HomeModule', data: { preload: true } }, // 懒加载 + 预加载 { path: '**', component: PageNotFoundComponent } // 注意要放到最后 ]; @NgModule({ imports: [ RouterModule.forRoot(appRoutes,{ enableTracing: true, // <-- debugging purposes only preloadingStrategy: SelectivePreloadingStrategy // 预加载 }) ], exports: [ RouterModule ], providers: [ CanDeactivateGuard, SelectivePreloadingStrategy ] }) export class AppRoutingModule { }
4. Sub-routing creation steps ( No instructions to create, directly manual)
(1) Create a new main folder Directory main<div>下面的区域是另一个路由出口</div> <router-outlet></router-outlet><!--此处依照下面的路由配置,默认显示AComponent组件的内容-->
(1). Configure the routing under the folder main in main-routing.module.ts. You need to reference the component of each component (the component that needs to be configured with routing)
import {NgModule} from '@angular/core'; import {RouterModule, Routes} from '@angular/router'; import {MainComponent} from './main.component'; import{AComponent} from './A/A.component'; import{BComponent} from './B/B.component'; const mainRoute: Routes = [ { path: '', component: MainComponent, data: { title: '面试预约', }, children: [ { path: '',//path为空表示默认路由 component: AComponent, data: { title: '大活动', } }, { path: 'activity', component: BComponent, data: { title: '中活动', } } ] } ]; @NgModule({ imports: [ RouterModule.forChild(mainRoute) ], exports: [ RouterModule ] }) export class MainRoutingModule{ }
(2), main.service.ts is generally used to place http requests
import { AppService } from './../../app.service'; import { Observable } from 'rxjs/Observable'; import { Injectable } from '@angular/core'; import { HttpParams } from '@angular/common/http'; import { PageData, ActivitysManage } from './model/activitys-manage'; import { BehaviorSubject } from 'rxjs'; import {PageDataBig, ActivitySmall, PageDataSmall } from './model/activitys-manage'; @Injectable() export class MainService { }
main文件夹下的组件如要调用MainService,需要在组件的ts文件引入MainService
(3)、在main.module.ts中引入各组件(包括自身、路由配置文件所用到的所有组件以及路由的module)
import { FormsModule } from '@angular/forms'; import { CommonModule } from '@angular/common'; import { MainComponent } from './interview-appointment.component'; import { AComponent } from './A/A.component'; import { BComponent } from './B/B.component'; import { NgModule } from '@angular/core'; import { CoreFrameCommonModule } from '../../common/common.module'; import { MainRoutingModule } from './main-routing.module'; import { NgZorroAntdModule } from '../../zorro/ng-zorro-antd.module'; import { MainService } from './interview-appointment.service'; @NgModule({ imports: [FormsModule,CoreFrameCommonModule, CommonModule, MainRoutingModule,NgZorroAntdModule], exports: [], declarations: [MainComponent,AComponent,BComponent], providers: [MainService], }) export class MainModule{ }
更多编程相关知识,请访问:编程视频!!
The above is the detailed content of A brief discussion on preloading configuration and lazy loading configuration in Angular. For more information, please follow other related articles on the PHP Chinese website!