@Host装饰器如何在注入器树中工作
How does @Host decorator work in injector tree
我正在尝试了解 @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'
。为什么?
Specifies that an injector should retrieve a dependency from any injector until reaching the host element of the current component.
https://angular.io/docs/ts/latest/api/core/index/Host-decorator.html
在我看来它会寻找提供者并在它到达组件的注入器后停止寻找。
Host
在普通 ReflectiveInjector.resolveAndCreate
注入器的上下文中没有语义意义。
It is just ignored 在编译器外部使用时。
对于所需的行为,
I expected to get an error, because as I understand the host for grandchild injector is child, and there is no Dependency provided in the child injector.
考虑改用 Self
。
我正在尝试了解 @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'
。为什么?
Specifies that an injector should retrieve a dependency from any injector until reaching the host element of the current component.
https://angular.io/docs/ts/latest/api/core/index/Host-decorator.html
在我看来它会寻找提供者并在它到达组件的注入器后停止寻找。
Host
在普通 ReflectiveInjector.resolveAndCreate
注入器的上下文中没有语义意义。
It is just ignored 在编译器外部使用时。
对于所需的行为,
I expected to get an error, because as I understand the host for grandchild injector is child, and there is no Dependency provided in the child injector.
考虑改用 Self
。