简体   繁体   中英

Angular 9 DI troubles

I have a service

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

I have a custom directive which use this service:

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

And also I have a html element which has that directive:

<div class="square small-square" [appIfViewportSize]="'small'">
        Small
</div>

And I have next error in console:

AppComponent.html:6 ERROR NullInjectorError: StaticInjectorError(AppModule)[String]: StaticInjectorError(Platform: core)[String]: NullInjectorError: No provider for String. at NullInjector.get...

My app.module:

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, HelloComponent, TestComponent, IfViewportSizeDirective ],
  bootstrap:    [ AppComponent ],
  providers: [BrowserWidthService]
})
export class AppModule { }

How can I fix it?

Dont use constructor params for initializing service prop's.They are intended for dependency injection.Use a different method to set the config value.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM