Angular 2 passing parameters to constructor throws DI exception

假装没事ソ 提交于 2020-01-13 08:14:48

问题


I'm wanting to setup a string property on a component in my constructor, but when I try something like this

@Component({
    selector: 'wg-app',
    templateUrl: 'templates/html/wg-app.html'
})
export class AppComponent {

    constructor(private state:string = 'joining'){

    }
}

I get a DI Exception

    EXCEPTION: No provider for String! (AppComponent -> String)

Clearly, the injector is trying to find a 'string' provider, and can't find any.

What sort of pattern should I be using for this type of thing? Eg. passing initial parameters to a component.

Should it be avoided? Should I be Injecting the initial string?


回答1:


You can use @Input() properties.

<my-component [state]="'joining'"></my-component>

export class AppComponent {
  @Input() state: string;
  constructor() { 
    console.log(this.state) // => undefined
  }
  ngOnInit() {
    console.log(this.state) // => 'joining'
  }
}

Constructor should generally be used just for DI...

But if you really, really need it you can create injectable variable (plunker):

let REALLY_IMPORTANT_STRING = new OpaqueToken('REALLY_IMPORTANT_STRING');
bootstrap(AppComponent, [provide(REALLY_IMPORTANT_STRING, { useValue: '!' })])

export class AppComponent {
  constructor(@Inject(REALLY_IMPORTANT_STRING) public state: REALLY_IMPORTANT_STRING) { 
    console.log(this.state) // => !
  }
}

Simplest option is to just set class property:

export class AppComponent {
  private state:string = 'joining';
  constructor() { 
    console.log(this.state) // => joining
  }
}

As @Mark pointed out, another option is to use a service:

export class AppService {
  public state:string = 'joining';
}
export class AppComponent {
  constructor(private service: AppService) { 
    console.log(this.service.state) // => joining
  }
}


来源:https://stackoverflow.com/questions/35518141/angular-2-passing-parameters-to-constructor-throws-di-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!