javascript - 手动触发模块延迟加载 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);
})
}
解决方案
Angular CLI 捆绑器基于两件事捆绑模块:
1) 如果您设置了延迟加载的模块 ( loadChildren
),它将单独捆绑模块并延迟提供。
2)但是,如果在任何其他模块中有对延迟加载模块的任何引用(通过将其添加到其imports
数组中),它将将该模块与引用的组件捆绑在一起。
所以应该发生的是,如果您的事件模块是从组件中引用的,它应该与该组件捆绑在一起。
您是否在imports
包含引用它的组件的模块的数组中引用了该模块?
你到底得到了什么错误?
顺便说一句 - 我在本次演讲的“延迟加载”部分对此进行了介绍:https ://www.youtube.com/watch?v=LaIAHOSKHCQ&t=1120s
推荐阅读
- c - 《Numerical Recipes in C》一书中的 Stiff Rosenbrock 方法实现
- flutter - 如何在特定时间运行飞镖代码,即使应用程序没有运行颤振
- json - 如何在谷歌结构化数据 Json 中使用 If 和 else
- c - 用于 arm 的 aarch64-linux-gnu-gcc 交叉编译器失败
- go - 如何优化 Go 中的线程安全队列?
- python - Python:基于多个分组对唯一变量进行分组和计数,无需重新计数
- php - 在流明中制作忘记密码
- python - Python类以点表示法返回字典列表
- c++ - 在 iOS 中为 C++ 编译 Protobuf 时出错:“未定义符号”和“ld:警告:忽略文件”
- javascript - 无法在 reducer 中迭代处于状态的数组