[英]Angular 9 DI troubles
我有服务
@Injectable({
providedIn: 'root'
})
export class BrowserWidthService {
viewportWidth: number;
config: IConfig;
actualValue: string;
constructor(@Inject(String) private configValue: string) {
this.viewportWidth = window.innerWidth;
this.config = config;
this.configValue = configValue;
}
我有一个使用此服务的自定义指令:
@Directive({
selector: '[appIfViewportSize]'
})
export class IfViewportSizeDirective implements OnInit {
@Input('appIfViewportSize') viewportWidth: string;
constructor(
private width: BrowserWidthService,
private elmRef: ElementRef,
private renderer: Renderer2)
{
this.width = new BrowserWidthService(this.viewportWidth);
}
ngOnInit() {
if (this.width.shouldRender())
console.log('rendered');
}
}
而且我还有一个具有该指令的 html 元素:
<div class="square small-square" [appIfViewportSize]="'small'">
Small
</div>
我在控制台中有下一个错误:
AppComponent.html:6 错误 NullInjectorError:StaticInjectorError(AppModule)[String]:StaticInjectorError(Platform:core)[String]:NullInjectorError:没有提供字符串。 在 NullInjector.get...
我的应用程序模块:
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent, HelloComponent, TestComponent, IfViewportSizeDirective ],
bootstrap: [ AppComponent ],
providers: [BrowserWidthService]
})
export class AppModule { }
我该如何解决?
不要使用构造函数参数来初始化服务属性。它们用于依赖注入。使用不同的方法来设置配置值。
@Injectable({
providedIn: 'root'
})
export class BrowserWidthService {
viewportWidth: number;
config: IConfig;
actualValue: string;
private configValue: string
constructor() {
this.viewportWidth = window.innerWidth;
this.config = config;
}
setConfigValue(value){
this.configValue = value;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.