首页 > 解决方案 > 手动触发模块延迟加载 Angular 7

问题描述

官方文档有很多关于如何延迟加载 Angular 模块的信息。[链接在这里]

const routes: Routes = [
  {
    path: 'customers',
    loadChildren: './customers/customers.module#CustomersModule'
  },
  {
    path: 'orders',
    loadChildren: './orders/orders.module#OrdersModule'
  },
  {
    path: '',
    redirectTo: '',
    pathMatch: 'full'
  }
];

这基本上使模块在用户访问/customers/orders路由时加载。

但是,我不知道如何从另一个模块加载模块。

在我的应用程序中,我有这些模块:

我的(个人资料页面)的一条路线auth module必须使用来自events module.

我的代码如下所示:

import { Observable } from 'rxjs';

import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';

import { AppState } from '../../app.store';
import { IUser } from '../auth.api.service';
import { selectUser } from '../store/auth.selectors';
import { IEvent } from '../../events/events.api.service';
import { selectAllEvents, selectIsLoading } from '../../events/store/events.selectors';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.scss'],
})
export class ProfileComponent implements OnInit {
  isLoading$: Observable<boolean>;
  events$: Observable<IEvent[]>;
  user$: Observable<IUser>;

  constructor(
    private store: Store<AppState>,
  ) {
    this.user$ = this.store.select(selectUser);
    this.isLoading$ = this.store.select(selectIsLoading);
    this.events$ = this.store.select(selectAllEvents);
  }

  ngOnInit() {
  }

}

但是,正如您所料,此代码不起作用。因为../../events还没有加载。如何手动加载模块?就像是:

constructor(
  private store: Store<AppState>,
) {
  this.user$ = this.store.select(selectUser);
  this.loadModule('../../events/events.module.ts').then(() => {
    this.isLoading$ = this.store.select(selectIsLoading);
    this.events$ = this.store.select(selectAllEvents);  
  })
}

标签: javascriptangularlazy-loading

解决方案


Angular CLI 捆绑器基于两件事捆绑模块:

1) 如果您设置了延迟加载的模块 ( loadChildren),它将单独捆绑模块并延迟提供。

2)但是,如果在任何其他模块中有对延迟加载模块的任何引用(通过将其添加到其imports数组中),它将将该模块与引用的组件捆绑在一起。

所以应该发生的是,如果您的事件模块是从组件中引用的,它应该与该组件捆绑在一起。

您是否在imports包含引用它的组件的模块的数组中引用了该模块?

你到底得到了什么错误?

顺便说一句 - 我在本次演讲的“延迟加载”部分对此进行了介绍:https ://www.youtube.com/watch?v=LaIAHOSKHCQ&t=1120s


推荐阅读