【发布时间】:2020-04-06 17:18:35
【问题描述】:
我有服务
@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(平台:核心)[字符串]: NullInjectorError:没有字符串的提供者! 在 NullInjector.get ...
我的 app.module:
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent, HelloComponent, TestComponent, IfViewportSizeDirective ],
bootstrap: [ AppComponent ],
providers: [BrowserWidthService]
})
export class AppModule { }
我该如何解决?
【问题讨论】:
-
为什么你在服务的构造函数中有@Inject(String) ......似乎是个问题
-
@Supercool。只是我尝试修复它,如果我删除它没有任何变化
-
不要在构造函数中使用 configvalue 将其移动到属性部分。构造函数参数用于依赖注入
-
在服务的其他函数中设置配置值
标签: angular