【发布时间】:2020-01-03 02:42:49
【问题描述】:
让我们来看看场景:
App.module
|__Lazy1.module
| \__LazyService1.module
|__Lazy2.module
| \__LazyService1.module
\__(many more)
目标是让LazyService1.module 为Lazy1/2.module 提供单例实例,但仅在获取 Lazy1/Lazy2 时才需要加载。
Angular 只创建和解析根 DI 上下文一次。任何后续上下文(对于惰性模块)都是子上下文。我的问题是我不想在App.module 中提供服务(LazyService1.module)(这是一个大模块,并且只被 2 个延迟加载的模块使用),所以逻辑上我的LazyService1.module 不会在根 DI 中解决上下文。
我需要以某种方式在 2 个延迟加载的模块之间共享 DI 上下文,而不必使其成为根依赖项(在 App.module 中)。
有没有办法定义共享 DI?一个模块可以访问其他模块的 DI 上下文吗?
是否可以在根目录下提供延迟加载服务供其他延迟加载模块使用,而不需要从根目录App.module 提供?
至于堆栈 - 我不认为我可以提供堆栈,因为我不知道它的外观。我可以实现一个热切在根目录下提供服务,但这不是这里的问题。
编辑 2:
App.module:
@NgModule({
declarations: [
AppComponent,
],
imports: [
// Used by all:
BrowserModule,
BrowserAnimationsModule,
CommonModule,
HttpClientModule,
// App router:
AppRoutingModule
],
bootstrap: [AppComponent]
})
export class AppModule { }
延迟加载路由模块:
const routes: Routes = [
{ path: 'admin', loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule) },
{ path: 'main', loadChildren: () => import('./main/main.module').then(m => m.MainModule) },
... many others, lazy or not
];
服务模块:
@NgModule({
providers: [
AuthenticationService
],
declarations: [...],
exports: [...],
imports: [
CommonModule,
]
})
export class SecurityModule { }
服务:
@Injectable()
export class AuthenticationService { ... }
然后我们有两个懒惰的:admin 和 main。
如果我要像这样导入SecurityModule:
@NgModule({
imports: [
SecurityModule
]
})
export class MainModule { }
我最终会为 Main 和 Admin 提供单独的 AuthenticationService。
如果我在App.module 中导入它,确定它可以工作,但我必须加载巨大的SecurityModule,它只需要在可能永远无法访问的 Main/Admin 中。
【问题讨论】:
-
我认为你不需要在
AppModule中导入ServiceModule,如果它只会被Lazy1Module使用。您可以在 stackbliktz.com 上创建一个示例吗? -
@ShashankVivek 重写了整个问题,以在惰性场景中更多地指向 DI 上下文。
标签: angular typescript lazy-loading angular8