[英]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.