程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了如何思考 Angular 中的延迟加载大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决如何思考 Angular 中的延迟加载?

开发过程中遇到如何思考 Angular 中的延迟加载的问题如何解决?下面主要结合日常开发的经验,给出你关于如何思考 Angular 中的延迟加载的解决方法建议,希望对你解决如何思考 Angular 中的延迟加载有所启发或帮助;

我在 Angular 中有一个相对较大的项目,除了两个登录页面之外,我还延迟加载了每个组件。

但我在项目中也有很多博客文章,它们获得了大量自然流量,当它们延迟加载时,即使直接访问它们也会减慢加载时间。

无论如何延迟加载它们是一种好习惯吗?

我问的原因是因为如果我不延迟加载,main.Js 往往会太大。

谢谢!

解决方法

嗨,我认为更好的方法是在后台预加载模块,例如: 创建选择性策略:

  import { Injectable } from '@angular/core';
import { PreloadingStrategy,Route } from '@angular/router';
import { loadavg } from 'os';
import { Observable,of } from 'rxjs';

@Injectable({
  providedIn: 'root',})
export class SelectiveStrategyService implements PreloadingStrategy {
  constructor() {}
  preload(route: Route,load: () => Observable<any>): Observable<any> {
    if (route.data && route.data['preload']) {
      return load();
    }
    return of(null);
  }
}

然后只加载需要的模块:

import { NgModule } from '@angular/core';
import {
  Routes,RouterModule,PreloadAllModules,PreloadingStrategy,} from '@angular/router';
import { SelectiveStrategyService } from './selective-strategy.service';

const routes: Routes = [
  {
    path: 'administration',loadChildren: () =>
      import('./administration/shell/shell.module').then((m) => m.ShellModule),// pass preload to true on the needed module
    data: { preload: true },},{
    path: 'clients',loadChildren: () =>
      import('./client/client.module').then((m) => m.ClientlModule),{ path: '**',redirectTo: '/administration',pathMatch: 'full' },];

@NgModule({
  imports: [
    RouterModule.forRoot(routes,{
      preloadingStrategy: SelectiveStrategyService,}),],exports: [RouterModule],})
export class AppRoutingModule {}

大佬总结

以上是大佬教程为你收集整理的如何思考 Angular 中的延迟加载全部内容,希望文章能够帮你解决如何思考 Angular 中的延迟加载所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: