[英]How to use Ngxs is a standalone component?
是否可以在独立组件中使用 Ngxs? 我尝试通过以下方式导入NgxsModule
:
@Component({
...
imports: [
...
NgxsModule.forFeature([MyState]),
...
和
@Component({
...
imports: [
...
NgxsModule.forRoot([MyState]),
...
但两者都给我以下错误消息: Type 'ModuleWithProviders<NgxsFeatureModule>' is not assignable to type 'any[] | Type<any>'
Type 'ModuleWithProviders<NgxsFeatureModule>' is not assignable to type 'any[] | Type<any>'
(或在NgxsRootModule
情况下为forRoot
)。 还提供了一条更深入的错误消息: 'imports' contains a ModuleWithProviders value, likely the result of a 'Module.forRoot()'-style call. These calls are not used to configure components and are not valid in standalone component imports - consider importing them in the application bootstrap instead.
'imports' contains a ModuleWithProviders value, likely the result of a 'Module.forRoot()'-style call. These calls are not used to configure components and are not valid in standalone component imports - consider importing them in the application bootstrap instead.
这是否受支持,我的语法有误吗? 还是不支持? 如果不支持,阻止程序是什么?
是的,它受支持。
正如您在Angular 独立组件指南中所见:
独立引导操作基于显式配置用于依赖注入的提供程序列表。 然而,现有的库可能依赖 NgModules 来配置 DI。 例如,Angular 的路由器使用 RouterModule.forRoot() 帮助程序在应用程序中设置路由。
所以你可以像他们解决路由器问题一样解决问题:
bootstrapApplication(AppComponent, { providers: [ importProvidersFrom(NgxsModule.forRoot([MyState])), //... ] });
您可以在引导程序 function 中使用来自'@angular/core'
NgxsModule.forRoot()
importProvidersFrom()
importProvidersFrom() (与我之前写的 SilasDerProfi 相同)
在你的 main.ts 里面:
bootstrapApplication(
AppComponent,
{
providers: [
importProvidersFrom(
NgxsModule.forRoot(
[MyState, SidebarState, CoreState],
{
developmentMode: !environment.production,
selectorOptions: {
suppressErrors: false,
injectContainerState: false
}
}
),
NgxsResetPluginModule.forRoot(),
// devtools always last
NgxsReduxDevtoolsPluginModule.forRoot()
)
]
}
).catch(err => console.error(err));
您可以在声明路线时设置惰性 Loaded forFeature([FooState])
:
延迟加载路由的完整示例:
export default <Routes>[
{
path: '',
loadComponent:
() => import('./foo-list/foo-list.component')
.then(mod => mod.FooListComponent),
providers: [
importProvidersFrom(
NgxsModule.forFeature([FooOverviewState])
)
],
canActivate: [AutoLoginPartialRoutesGuard],
},
{
path: 'add',
loadComponent:
() => import('./foo-item-add/foo-item-add.component')
.then(mod => mod.FooItemAddComponent),
providers: [
importProvidersFrom(
NgxsModule.forFeature([FooState])
)
],
canActivate: [AutoLoginPartialRoutesGuard],
canDeactivate: [CanDeactivateComponentGuard]
},
{
path: ':id',
loadComponent:
() => import('./foo-item-edit/foo-item-edit.component')
.then(mod => mod.FooItemEditComponent),
providers: [
importProvidersFrom(
NgxsModule.forFeature([FooState])
)
],
canActivate: [AutoLoginPartialRoutesGuard],
canDeactivate: [CanDeactivateComponentGuard]
}
];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.