


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 { }
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()); } }
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 { }
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); } } }
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!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



This article continues the learning of Angular, takes you to understand the metadata and decorators in Angular, and briefly understands their usage. I hope it will be helpful to everyone!

This article will give you an in-depth understanding of Angular's state manager NgRx and introduce how to use NgRx. I hope it will be helpful to you!

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

Do you know Angular Universal? It can help the website provide better SEO support!

With the rapid development of the Internet, front-end development technology is also constantly improving and iterating. PHP and Angular are two technologies widely used in front-end development. PHP is a server-side scripting language that can handle tasks such as processing forms, generating dynamic pages, and managing access permissions. Angular is a JavaScript framework that can be used to develop single-page applications and build componentized web applications. This article will introduce how to use PHP and Angular for front-end development, and how to combine them

This article will share with you an Angular practical experience and learn how to quickly develop a backend system using angualr combined with ng-zorro. I hope it will be helpful to everyone!

How to use monaco-editor in angular? The following article records the use of monaco-editor in angular that was used in a recent business. I hope it will be helpful to everyone!

PHP is a very popular programming language, and CodeIgniter4 is a commonly used PHP framework. When developing web applications, using frameworks is very helpful. It can speed up the development process, improve code quality, and reduce maintenance costs. This article will introduce how to use the CodeIgniter4 framework. Installing the CodeIgniter4 framework The CodeIgniter4 framework can be downloaded from the official website (https://codeigniter.com/). Down
