我知道这个问题可能看起来微不足道,但事实并非如此。让我解释一下。对于一个向其所有子组件提供instacne的组件来说,这很简单,您只需这样做:
@Component({
selector: 'Starwars',
directives: [ShoppingComponent],
template: `<shopping></shopping>`,
providers: [CartActions]
})但是,我正在尝试与我的组件的子组件共享一个实例,该实例是我通过new..如下所示:
export class Starwars {
private appStore:any;
constructor() {
this.appStore = new AppStore();
// tried this with no luck
var injector = Injector.resolveAndCreate([
provide(AppStore, {useValue: this.appStore})
]);
// tried this with no luck
provide(AppStore, {useFactory: () => {
return this.appStore;
}})
}
}还尝试了这些,但没有成功:
@Component({
selector: 'Starwars',
directives: [ShoppingComponent],
template: `<shopping></shopping>`,
providers: [CartActions, PartActions,
provide(AppStore, {useValue: this.appStore})
]
})还有useClass..。因此,正如我所说的,我正在尝试与我的组件的子级共享一个手动实例化的类,而不是我依赖注入并让Angular2为我实例化的组件……
发布于 2016-01-23 03:46:54
这是AFIK在角度2中不可能的。
例如,有一些方法可以在运行时通过DynamicComponentLoader动态注入组件。但我们不能覆盖该组件的提供者,它们在组件元数据中,在运行时通过闭包受到保护,并且无法编辑。也没有与依赖注入相关的生命周期钩子。
根本没有机制允许你尝试做什么,而实际上有机制来避免它,比如将提供者设为只读。也没有允许在运行时从组件调用的提供程序类型。
看起来你正在尝试的东西在设计上是不可能的。这可能是件好事,因为它避免了依赖注入机制被以意想不到的方式使用。
https://stackoverflow.com/questions/34953385
复制相似问题