英文:
Using the Angular inject function with a APP_INITIALIZER
问题
使用Ivy,Angular引入了inject
函数。根据文档,该函数可以与以下示例一起“从提供程序的工厂中”使用:
providers: [
{
provide: Car,
useFactory: () => {
// OK: a class factory
const engine = inject(Engine);
return new Car(engine);
}
}
]
这让我相信我现在可以将我的旧APP_INITIALIZER
转换为这样的东西:
providers: [
{
provide: APP_INITIALIZER,
useFactory: (engine: Engine) => () => engine.start(),
deps: [Engine],
multi: true
}
]
使用inject
函数来简化如下:
providers: [
{
provide: APP_INITIALIZER,
useFactory: () => () => inject(Engine).start(),
multi: true
}
]
然而,这会导致以下错误消息:
错误:NG0203:必须从注入上下文中调用inject(),如构造函数、工厂函数、字段初始化程序或与
EnvironmentInjector#runInContext
一起使用的函数。
在使用APP_INITIALIZER
时,不再是工厂上下文吗?或者问题是什么?
英文:
With Ivy, Angular introduced the nice inject
function.
According to the documentation the function can be used "from a provider's factory" accompanied with the following example:
providers: [
{
provide: Car,
useFactory: () => {
// OK: a class factory
const engine = inject(Engine);
return new Car(engine);
}
}
]
This makes me believe that I can now convert my old APP_INITIALIZER
s:
providers: [
{
provide: APP_INITIALIZER,
useFactory: (engine: Engine) => () => engine.start(),
deps: [Engine],
multi: true
}
]
using the inject
function to something simpler like this:
providers: [
{
provide: APP_INITIALIZER,
useFactory: () => () => inject(Engine).start(),
multi: true
}
]
This fails, however, giving me the following error message:
> Error: NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with EnvironmentInjector#runInContext
.
Is it no longer a factory context, when using APP_INITIALIZER
? Or what is the problem here?
答案1
得分: 1
这似乎是一个缺失的功能,上下文仅存在于顶级函数中。
这是一个有效的示例:
providers: [
{
provide: APP_INITIALIZER,
useFactory: () => {
const engine = inject(Engine);
return () => engine.start();
},
multi: true
}
]
或者
providers: [
{
provide: APP_INITIALIZER,
useFactory: () => {
inject(Engine).start();
return () => {};
},
multi: true
}
]
英文:
Looks like a missing feature, context exists only in the top level function.
This is working example:
providers: [
{
provide: APP_INITIALIZER,
useFactory: () => {
const engine = inject(Engine);
return () => engine.start();
},
multi: true
}
]
Or
providers: [
{
provide: APP_INITIALIZER,
useFactory: () => {
inject(Engine).start();
return () => {};
},
multi: true
}
]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论