The NgModule is the core of an Angular module.

Functions of 1.@NgModule:

  • The fundamental purpose of an NgModule is to help developers organize business code. It is important that developers use an NgModule to organize closely related components together.
  • Ngmodules are used to control whether components, directives, pipes, etc. can be used. Components in the same NgModule are visible to each other by default, while external components can only see the contents of NgModule exports. If you define an NgModule that does not export anything, then an external user who imports your module cannot use anything defined inside it.
  • Ngmodules are the smallest unit of packaging that checks all @ NgModules and routing configurations. Angular uses WebPack packaging underneath. Because Angular has already configured webPack for us, it’s a lot easier for developers who would otherwise have to configure the environment themselves.
  • An NgModule is the smallest unit the Router can load asynchronously, and the smallest unit the Router can load is a module, not a component. Of course, it is permissible to have only one component in a module, and many component libraries do this.

2.@NgModule Structure Description:

@NgModule({declarations: [], // Imports of components, directives, and pipes that belong to the current module: [],// Declare the application to other modules using providers: [],// Inject services into the current module bootstrap: []// Which component starts by default (only the root module can set the bootstrap property)})Copy the code

3. Lazy loading instructions

The RouterModule object provides two static methods forRoot() and forChild() to configure routing information.

  • ForRoot ()// Defines the main routing information in the main module
  • forChild()``//Applied to feature modules (submodules)

(2) lazy: loadChildren

Instead of adding the module to the AppModule, the loadChildren attribute tells Angular to load the module along the path specified by the loadChildren attribute. This is the specific application of module lazy loading. Modules are loaded only when the user accesses/XXX /** path, which reduces the size of resources to be loaded when the application starts. The loadChildren attribute value consists of three parts:

  • You need to import the relative path of the Module
  • # delimiter
  • The name of the exported module class

(3) preloading

In the case of lazy loading, the route sometimes responds with a delay when loading a module for the first time. This is where a preloading strategy can be used to solve the problem.

Angular provides two loading strategies,

  • PreloadAllModules– preload
  • NoPreloading– No preloading (default).

The second parameter to RouterModule.forroo () adds configuration options, including a preloadingStrategy configuration, which is a preload policy configuration.

Import {NgModule} from '@angular/core'; 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 the code

However, we prefer to control the preloading of modules ourselves, so we need to customize the preloading strategy

A. Customize – All modules will be loaded in 5 seconds

Create a new custom-preloading-strategy.ts file at the same level as the app component

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 the code

Inject the app. Modules. Ts providers

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 { }
Copy the code

 

B. Custom – Specifies module preloading

Create a selective-preloading-strategy.ts file at the peer level of the app component (inject providers in app-routing.module.ts, and set preloading of data defined in the route with additional parameters).

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); }}}Copy the code

 

App-routing.module. ts (lazy loading of this file combined 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'; // Preload import {PageNotFoundComponent} from './not-found.component'; const appRoutes: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'full'}, { path: 'mian', loadChildren: './main/mian. Module# MainModule'}, // lazy loading (router configuration files and module files at this level do not need to import this component) {path: 'home', loadChildren: './home/home.module#HomeModule', data: {preload: true}}, // lazy + preload {path: '**', Component: PageNotFoundComponent} // Be sure to put it last]; @NgModule({imports: [RouterModule.forRoot(appRoutes,{enableTracing: True, // <-- debugging purposes only preloadingStrategy: SelectivePreloadingStrategy / / preload})], exports: [RouterModule], will: [CanDeactivateGuard, SelectivePreloadingStrategy]}) export class AppRoutingModule {}Copy the code

 

4. Child route creation steps (manual creation without instruction)

(1) Create a home folder

The main directory

  • main.component.html

  • main.component.scss

  • main.component.ts

  • main.module.ts

  • main-routing.module.ts

  • main.service.ts

    • A directory
      • A.component.html
      • A.component.scss
      • A.component.ts
    • Directory B
      • B.component.html
      • B.component.scss
      • B.component.ts

 

Main.component.html, for example, has a section for subviews.

The area below <div> is another routing outlet </div> <router-outlet></router-outlet><! The AComponent component is displayed by default.Copy the code

(1) Configure routes in main-routing.module.ts folder main. Reference components (components that need 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: ''] Component: AComponent, data: {title: 'big activity',}}, {path: 'activity', Component: BComponent, data: {title: 'active ',}}]}]; @NgModule({ imports: [ RouterModule.forChild(mainRoute) ], exports: [ RouterModule ] }) export class MainRoutingModule{ }Copy the code

(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 { }Copy the code

To invoke MainService for components in the main folder, import MainService to the ts file of the component

(3) Introduce components in main.module.ts (including itself, all components used by routing configuration files and routing modules)

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{ }Copy the code

\