Host
类构造函数的视图提供者参数上的参数修饰器,用于指示 DI 框架通过检查子元素的注入器来解析视图,并在到达当前组件的宿主元素时停止。
Parameter decorator on a view-provider parameter of a class constructor that tells the DI framework to resolve the view by checking injectors of child elements, and stop when reaching the host element of the current component.
使用说明
以下显示了与 @Optional
装饰器一起使用的情况,并允许空结果。
The following shows use with the @Optional
decorator, and allows for a null
result.
class OtherService {}
class HostService {}
@Directive({selector: 'child-directive'})
class ChildDirective {
logs: string[] = [];
constructor(@Optional() @Host() os: OtherService, @Optional() @Host() hs: HostService) {
// os is null: true
this.logs.push(`os is null: ${os === null}`);
// hs is an instance of HostService: true
this.logs.push(`hs is an instance of HostService: ${hs instanceof HostService}`);
}
}
@Component({
selector: 'parent-cmp',
viewProviders: [HostService],
template: '<child-directive></child-directive>',
})
class ParentCmp {
}
@Component({
selector: 'app',
viewProviders: [OtherService],
template: '<parent-cmp></parent-cmp>',
})
class App {
}
有关扩展的示例,请参见“依赖项注入指南” 。
For an extended example, see "Dependency Injection Guide".