【问题标题】:Angular 9 DI troublesAngular 9 DI 问题
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2020-06-21
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 2020-05-16
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 2020-06-24
    相关资源
    最近更新 更多