手动触发模块延迟加载 Angular 7

Trigger Module Lazy Load Manually Angular 7

官方文档有很多关于如何延迟加载 angular 模块的信息。 [link here]

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 的 ngrx 商店。

我的代码如下所示:

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

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

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

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

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

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

你到底遇到了什么错误?

顺便说一句 - 我在本次演讲的 "lazy loading" 部分介绍了这一点:https://www.youtube.com/watch?v=LaIAHOSKHCQ&t=1120s

您不必担心加载 ../../events。由于您有 import 语句,因此 class/interface 将在模块中可用。如果出于某种原因,你想使用其他模块的功能,你可以在 @NgModule 声明中的 imports 数组中添加模块名称。