简单的案例,但到目前为止无法找出答案。
从角度 v4 尝试手动注入NgControl
:
this.injector.get(NgControl);
棉绒开始抱怨:
get is deprecated: from v4.0.0 use Type<T> or InjectionToken<T>
如何使用注射器正确注射?
(使用 Angular 8(这将通过而不会TSLint
错误:
this.injector.get<NgControl>(NgControl as Type<NgControl>);
但是,通过构造函数有一个更优雅的解决方案。
constructor(@Self() @Optional() public ngControl: NgControl) {
if(this.ngControl) {
this.ngControl.valueAccessor = this;
}
}
但是您需要记住,这是NG_VALUE_ACCESSOR
的内联(更优雅(替代品 - 使用两者时都会出现周期性依赖错误。
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => FieldComponent),
multi: true
}
你现在必须像这样使用它:
this.injector.get<NgControl>(NgControl);
请参阅角度文档:https://angular.io/api/core/Injector
get<T>(token: Type<T> | InjectionToken<T>, notFoundValue?: T, flags?: InjectFlags): T