0

I have a Typescript class where all its constructor parameters are optional. How can I pass a service to it, as it acts as a required parameter ?

Current Situation :

constructor(label ? : String, location ? : any) {...}

Sort of what I am looking for :

constructor(private myService: MyService, label ? : String, location ? : any) {...}
ypicard
  • 3,593
  • 3
  • 20
  • 34

2 Answers2

0

How can I pass a service to it, as it acts as a required parameter

You get an instance of the service using angular injector.

More

Get Injector : https://github.com/angular/angular/issues/4112#issuecomment-153811572

basarat
  • 261,912
  • 58
  • 460
  • 511
0

As @basarat mentioned you can use the Angular injector to "get" services which was explained here: Angular 2 conditionally inject service in component but this is not a suggested pattern as it seems from the comment section.


What you are looking for is explained here: https://angular.io/guide/dependency-injection#optional-dependencies

You can tell Angular that the dependency is optional by annotating the constructor argument with @Optional()

after annotating the dependency you simply do an if check in the constructor to see whether it's provided or not.

eko
  • 39,722
  • 10
  • 72
  • 98