装饰者的Angular 2依赖注入 [英] Angular 2 dependency injection for decorators
问题描述
有没有办法将服务依赖项注入到 @Component
装饰中,像这样?
Is there any way to inject a service dependency into a @Component
decoration, something like this?
@Component({
selector: injectedService.getPrefix() + 'my-component'
})
export class MyComponent { }
或者,如果没有,也许可以替代 @Component
并将依赖项注入子类以获得类似的结果?
Or, if not, might it be possible to subsclass @Component
and inject a dependency into the subclass to achieve a similar result?
推荐答案
更新> = RC.5 >
@NgModule({
...
})
export class AppModule {
ngDoBootstrap(moduleRef) {
appInjector(moduleRef.injector);
}
}
appInjector
实现,请参见下文
原始< = RC.5
Angular2不直接支持此功能。您可以将注入器存储在Angular应用程序外部,然后从那里引用它,如
( 柱塞示例 )
This is not directly supported by Angular2. You can store the injector outside of your Angular app and then reference it from there like demonstrated as a workaround for the @CanActivate()
decorator in https://github.com/angular/angular/issues/4112#issuecomment-153811572.
(Plunker example)
在 main.ts
中,将注入器分配给 appInjector
In main.ts
the injector is assigned to appInjector
bootstrap(App, [
Auth,
HTTP_PROVIDERS,
ROUTER_PROVIDERS,
provide(LocationStrategy, {useClass: HashLocationStrategy})
]).then((appRef: ComponentRef) => {
// store a reference to the application injector
appInjector(appRef.injector);
});
app-injector.ts
let appInjectorRef: Injector;
export const appInjector = (injector?: Injector):Injector => {
if (injector) {
appInjectorRef = injector;
}
return appInjectorRef;
};
然后您可以得到对注入器的引用,例如
then you can get a reference to the injector like
appInjector()...
这赢了如果在 bootstrap()
完成之前创建组件,则无法工作。
This won't work if the component is created before bootstrap()
is completed.
这篇关于装饰者的Angular 2依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!