Angular 9 DI неприятностей - PullRequest
       0

Angular 9 DI неприятностей

0 голосов
/ 06 апреля 2020

У меня есть служба

@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 ERROR NullInjectorError: StaticInjectorError (AppModule) [String]: StaticInjectorError (Платформа: ядро) [String]: NullInjectorError: Нет поставщика для строки! at NullInjector.get ...

Мой app.module:

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

Как я могу это исправить?

1 Ответ

1 голос
/ 06 апреля 2020

Не используйте параметры конструктора для инициализации служебных объектов. Они предназначены для внедрения зависимостей. Используйте другой метод для установки значения конфигурации.

@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;
  } 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...