【发布时间】:2017-07-06 18:21:27
【问题描述】:
我试图了解@Host 装饰器是如何与视图组件分离。所以我创建了以下注入器树:
class Dependency {
}
@Injectable()
class NeedsDependency {
constructor(@Host() public dependency: Dependency) {
console.log(this.dependency); // outputs 'A', but I expected the error
}
}
const parent = ReflectiveInjector.resolveAndCreate([{provide: Dependency, useValue: 'A'}]);
const child = parent.resolveAndCreateChild([]);
const grandchild = child.resolveAndCreateChild([NeedsDependency]);
grandchild.get(NeedsDependency);
我预计会出现错误,因为据我了解 grandchild 注入器的主机是 child,而 child 注入器中没有提供 Dependency。然而,当我运行这段代码时,我得到了从根注入器注入的'A'。为什么?
【问题讨论】:
-
在哪里提供
NeedsDependency(NgModel或Component)? -
本例中没有角框架,是解耦的
-
那么你不应该期望
@Host()有任何效果。 -
@GünterZöchbauer,我不太确定。
@Optional、@Self和@SkipSelfdo 等其他装饰器在与角度解耦时会起作用 -
当然,它们在与 Angular 一起使用时也独立于组件,但
@Host()与组件有直接关系。如果没有组件,如何找到组件的注入器?
标签: javascript angular angular2-di