• angular配置懒加载路由的思路


    前言

        本人记性不好,对于别人很容易记住的事情,我愣是记不住,所以还是靠烂笔头来帮我长长记性。

     参考文章:https://blog.csdn.net/xif3681/article/details/84584317

    正文

    NgModule作为Angular模块的核心,下面首先就来讲一讲。

    1.@NgModule的作用:

    • NgModule 最根本的意义是帮助开发者组织业务代码,开发者可以利用 NgModule 把关系比较紧密的组件组织到一起,这是首要的。
    • NgModule 用来控制组件、指令、管道等是否可以使用,处于同一个 NgModule 里面的组件默认互相可见,而对于外部的组件来说,只能看到 NgModule 导出( exports )的内容,也就是说,如果你定义的 NgModule 不 exports 任何内容,那么外部使用者即使 import 了你这个模块,也没法使用里面定义的任何内容。
    • NgModule 是打包时候用到的最小单位,打包的时候会检查所有 @NgModule 和路由配置,Angular底层是使用webpack打包。因为Angular已经帮我们配置好了webpack,所以开发者轻松很多,否则就需要自己配置环境。
    • NgModule 是 Router 进行异步加载的最小单位,Router 能加载的最小单位是模块,而不是组件。当然,模块里面只放一个组件是允许的,很多组件库都是这样做的。

    2.@NgModule结构说明:

    @NgModule({ 
      declarations: [], //属于当前模块的组件、指令及管道
      imports: [], //当前模板所依赖的项,即外部模块(包括httpModule、路由等)
      export:[],//声明出应用给其他的module使用
      providers: [], //注入服务到当前模块
      bootstrap: []//默认启动哪个组件(只有根模块才能设置bootstrap属性)
    })

    3.懒加载说明

    (1)RouterModule对象提供了两个静态的方法:forRoot()forChild()来配置路由信息。

    • forRoot()//在主模块中定义主要的路由信息
    • forChild()//应用在特性模块(子模块)中

    (2)懒加载:loadChildren

    此处并没有将对应的模块加入到AppModule中,而是通过loadChildren属性,告诉Angular路由依据loadChildren属性配置的路径去加载对应的模块。这就是模块懒加载功能的具体应用,当用户访问 /xxx/** 路径的时候,才会加载对应的模块,这减少了应用启动时加载资源的大小。 loadChildren的属性值由三部分组成:

    • 需要导入Module的相对路径
    • #分隔符
    • 导出模块类的名称

    (3)预加载

    在使用懒加载的情况下,路由第一次加载某个模块时,有时反应有延迟。这时就可以用预加载策略来解决这个问题。

    Angular提供了两种加载策略,

    • PreloadAllModules-预加载
    • NoPreloading-没有预加载(默认)。

    RouterModule.forRoo()第二个参数可以添加配置选项,配置选项中就有一个是preloadingStrategy配置,这个配置是一个预加载策略配置。

    //使用默认预加载-预加载全部模块
    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 { }

    但是,我们更喜欢自己去控制对模块的预加载,这时就需要自定义预加载策略

    A.自定义-5秒后加载所有模块

    在app组建的同级新建一个custom-preloading-strategy.ts文件

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

    在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 { }

    B.自定义-指定模块预加载

    在app组建的同级新建一个selective-preloading-strategy.ts文件(需要在app-routing.module.ts中的providers注入,然后在路由中定义的data通过附加参数来设置是否预加载

    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(此文件懒加载与预加载相结合)

    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.子路由创建步骤(没有靠指令创建,直接手动)

    (1)新建主文件夹

    目录main

    • main.component.html
    • main.component.scss
    • main.component.ts
    • main.module.ts
    • main-routing.module.ts
    • main.service.ts
        目录A
          A.component.html
          A.component.scss
          A.component.ts
        目录B
          B.component.html
          B.component.scss
          B.component.ts

     

    比如在上面main.component.html有个区域用于放子视图(以下我都先讲思路,再放关键代码,其他不赘述)

    <div>下面的区域是另一个路由出口</div>
    <router-outlet></router-outlet><!--此处依照下面的路由配置,默认显示AComponent组件的内容-->

    (1)在main-routing.module.ts里面配置文件夹main下的路由,需要引用各组件的component(需要配置路由的组件)

    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一般用于放http请求

    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{ }

    后续更新...

  • 相关阅读:
    Go interface{}、类型断言
    相关资料
    php实践
    安装zookeeper
    对象池化,对象池
    java getResourcesAsStream()如何获取WEB-INF下的文件流
    android--SDK Manager下载Connection to http://dl-ssl.google.com refused
    Intellij idea 切换SVN路径
    Intellij Idea @Autowired取消提示
    恢复文件默认打开方式
  • 原文地址:https://www.cnblogs.com/myyouzi/p/11840067.html
Copyright © 2020-2023  润新知