Angular 角度9 DI故障

Angular 角度9 DI故障,angular,Angular,我有服务 @Injectable({ providedIn: 'root' }) export class BrowserWidthService { viewportWidth: number; config: IConfig; actualValue: string; constructor(@Inject(String) private configValue: string) { this.viewportWidth = window.innerWidt

我有服务

@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>

如何修复它?

不要使用构造函数参数初始化服务属性。它们用于依赖项注入。请使用其他方法设置配置值

@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;
  } 

为什么在服务中的构造函数中有@Inject(String)……似乎是problem@Supercool. 只是我尝试修复它,如果我删除它,不会有任何改变。不要在构造函数中使用configvalue将其移动到属性部分。构造函数参数用于依赖项注入在服务中的其他函数内设置配置值
@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;
  }