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?
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With