我正在尝试了解如何从视图组件中耦合的 @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'
。为什么?
Host
在普通ReflectiveInjector.resolveAndCreate
注射器的上下文中没有语义含义。
在编译器外使用时,它只是被忽略。
对于所需的行为,
我期望会出错,因为我了解孙子的注射器是孩子,并且儿童注射器中没有依赖性。
考虑使用Self
而改。
指定喷油器应从任何注射器中检索依赖关系,直到到达当前组件的主机元素。
https://angular.io/docs/ts/latest/api/core/index/host-decorator.html
对我来说,它将寻找提供商,并停止照顾它到达组件的注射器。