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

Nov 05, 2021 am 10:13 AM
angular Routing configuration

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属性)
})
Copy after login

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 { }
Copy after login

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());
    }
}
Copy after login

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 { }
Copy after login

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);
    }
  }
}
Copy after login

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 { }
Copy after login

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组件的内容-->
Copy after login

(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{
}
Copy after login

(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 {
  
}
Copy after login

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{ }
Copy after login

更多编程相关知识,请访问:编程视频!!

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Let's talk about metadata and decorators in Angular Let's talk about metadata and decorators in Angular Feb 28, 2022 am 11:10 AM

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!

Detailed explanation of angular learning state manager NgRx Detailed explanation of angular learning state manager NgRx May 25, 2022 am 11:01 AM

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!

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

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

An article exploring server-side rendering (SSR) in Angular An article exploring server-side rendering (SSR) in Angular Dec 27, 2022 pm 07:24 PM

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

How to use PHP and Angular for front-end development How to use PHP and Angular for front-end development May 11, 2023 pm 04:04 PM

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

Angular + NG-ZORRO quickly develop a backend system Angular + NG-ZORRO quickly develop a backend system Apr 21, 2022 am 10:45 AM

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!

A brief analysis of how to use monaco-editor in angular A brief analysis of how to use monaco-editor in angular Oct 17, 2022 pm 08:04 PM

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!

How to use CodeIgniter4 framework in php? How to use CodeIgniter4 framework in php? May 31, 2023 pm 02:51 PM

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

See all articles