


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:
- 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 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- main.component .html
- main.component.scss
- main.component.ts
- main. module.ts
- main-routing.module.ts ##main.service.ts
-
Directory A
- A.component.html
- DirectoryB
- B.component.html
-
-
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) - A.component.html
<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!

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor