Home >Web Front-end >JS Tutorial >A brief discussion on preloading configuration and lazy loading configuration in Angular

A brief discussion on preloading configuration and lazy loading configuration in Angular

青灯夜游
青灯夜游forward
2021-11-05 10:13:552422browse

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!

A brief discussion on preloading configuration and lazy loading configuration in Angular

NgModule is the core of the Angular module. Let’s talk about it first.

1. The role of @NgModule:

  • The most fundamental meaning of NgModule is to help developers organize business code. Developers can It is primary to use NgModule to organize closely related components together.
  • NgModule is used to control whether components, instructions, pipes, etc. can be used. Components in the same NgModule are visible to each other by default. For external components, only the contents exported by NgModule can be seen. , that is to say, if the NgModule you define does not export any content, then external users will not be able to use any content defined in it even if they import your module.
  • NgModule is the smallest unit used when packaging. When packaging, all @NgModule and routing configurations will be checked. The bottom layer of Angular is packaged using webpack. Because Angular has already configured webpack for us, it is much easier for developers, otherwise they need to configure the environment themselves.
  • NgModule is the smallest unit that Router can load asynchronously. The smallest unit that Router can load is a module, not a component. Of course, it is allowed to place only one component in a module, and many component libraries do this. [Related tutorial recommendations: "angular tutorial"]

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:

  • The relative path of the Module that needs to be imported
  • #Separator
  • The name of the exported module class

(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-preloading
  • NoPreloading-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 strategy

A. 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 &#39;@angular/platform-browser&#39;;
import { NgModule } from &#39;@angular/core&#39;;

import { AppComponent } from &#39;./app.component&#39;;
import { HomeComponent } from &#39;./home/home.component&#39;;
import { routes } from &#39;./main.routing&#39;;
import { RouterModule } from &#39;@angular/router&#39;;
import { CustomPreloadingStrategy } from &#39;./preload&#39;;

@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 Preloading

Create 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 &#39;@angular/core&#39;;
import { PreloadingStrategy, Route } from &#39;@angular/router&#39;;
import { Observable} from &#39;rxjs/Observable&#39;;
import &#39;rxjs/add/observable/of&#39;;
@Injectable()
export class SelectivePreloadingStrategy implements PreloadingStrategy {
  preloadedModules: string[] = [];

  preload(route: Route, load: () => Observable<any>): Observable<any> {
    if (route.data && route.data[&#39;preload&#39;]) {
      return load();
    } else {
      return Observable.of(null);
    }
  }
}

app-routing.module.ts (This file combines lazy loading with preloading)

import { NgModule } from &#39;@angular/core&#39;;
import { RouterModule, Routes } from &#39;@angular/router&#39;;
import { CanDeactivateGuard } from &#39;./guard/can-deactivate-guard.service&#39;;
import { SelectivePreloadingStrategy } from &#39;./selective-preloading-strategy&#39;; // 预加载
import { PageNotFoundComponent } from &#39;./not-found.component&#39;;
const appRoutes: Routes = [
{ path: &#39;&#39;, redirectTo: &#39;home&#39;, pathMatch: &#39;full&#39;},
{ path: &#39;mian&#39;, loadChildren: &#39;./main/mian.module#MainModule&#39; }, // 懒加载(在这个层级的router配置文件及module文件都不需要引入该组建)
{ path: &#39;home&#39;, loadChildren: &#39;./home/home.module#HomeModule&#39;, data: { preload: true } }, // 懒加载 + 预加载
{ path: &#39;**&#39;, 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

  • main.component .html

  • main.component.scss

  • main.component.ts

  • main. module.ts

  • main-routing.module.ts

  • ##main.service.ts
  • Directory A
    • A.component.html
    • ##A.component.scss
    • A.component.ts
      • DirectoryB
    • B.component.html
    • B.component.scss
      ##B.component.ts
  • For example, in main.component.html above, there is an area for placing subviews (below I will talk about the ideas first, and then put the key code, Others will not be described in detail)
<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 &#39;@angular/core&#39;;
import {RouterModule, Routes} from &#39;@angular/router&#39;;
import {MainComponent} from &#39;./main.component&#39;;
import{AComponent} from &#39;./A/A.component&#39;;
import{BComponent} from &#39;./B/B.component&#39;;
const mainRoute: Routes = [
  {
    path: &#39;&#39;,
    component: MainComponent,
    data: {
      title: &#39;面试预约&#39;,
    },
    children: [
      {
        path: &#39;&#39;,//path为空表示默认路由
        component: AComponent,
        data: {
          title: &#39;大活动&#39;,
        }
      },
      {
        path: &#39;activity&#39;,
        component: BComponent,
        data: {
          title: &#39;中活动&#39;,
        }
      }
    ]
  }
];


@NgModule({
  imports: [
    RouterModule.forChild(mainRoute)
  ],
  exports: [
    RouterModule
  ]
})
export class MainRoutingModule{
}

(2), main.service.ts is generally used to place http requests

import { AppService } from &#39;./../../app.service&#39;;
import { Observable } from &#39;rxjs/Observable&#39;;
import { Injectable } from &#39;@angular/core&#39;;
import { HttpParams } from &#39;@angular/common/http&#39;;
import { PageData, ActivitysManage } from &#39;./model/activitys-manage&#39;;
import { BehaviorSubject } from &#39;rxjs&#39;;
import {PageDataBig, ActivitySmall, PageDataSmall } from &#39;./model/activitys-manage&#39;;
@Injectable()
export class MainService {
  
}

main文件夹下的组件如要调用MainService,需要在组件的ts文件引入MainService

(3)、在main.module.ts中引入各组件(包括自身、路由配置文件所用到的所有组件以及路由的module)

import { FormsModule } from &#39;@angular/forms&#39;;
import { CommonModule } from &#39;@angular/common&#39;;
import { MainComponent } from &#39;./interview-appointment.component&#39;;
import { AComponent } from &#39;./A/A.component&#39;;
import { BComponent } from &#39;./B/B.component&#39;;
import { NgModule } from &#39;@angular/core&#39;;
import { CoreFrameCommonModule } from &#39;../../common/common.module&#39;;
import { MainRoutingModule } from &#39;./main-routing.module&#39;;
import { NgZorroAntdModule } from &#39;../../zorro/ng-zorro-antd.module&#39;;
import { MainService } from &#39;./interview-appointment.service&#39;;
@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!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete