1

我试图了解@Host装饰器如何与view-components 分离。所以我创建了以下注入器树:

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,并且注入器中没有Dependency提供child。但是,当我运行此代码时,我会'A'从根注入器中注入。为什么?

4

2 回答 2

2

HostReflectiveInjector.resolveAndCreate在普通注入器的上下文中没有语义含义。

在编译器外部使用时会被忽略。

对于所需的行为,

我预计会出现错误,因为据我了解,孙子注入器的主机是子代,并且子代注入器中没有提供依赖项。

考虑Self改用。

于 2017-02-17T11:03:44.147 回答
0

指定注入器应从任何注入器检索依赖项,直到到达当前组件的宿主元素。

https://angular.io/docs/ts/latest/api/core/index/Host-decorator.html

在我看来,它会寻找提供者并在它到达组件的注入器后停止寻找。

于 2017-02-17T09:38:02.107 回答