Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 passing parameters to constructor throws DI exception

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?

like image 593
Simon Trewhella Avatar asked Feb 20 '16 01:02

Simon Trewhella


1 Answers

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
  }
}
like image 78
Sasxa Avatar answered Oct 28 '22 05:10

Sasxa