DI constructor with optional parameters DI constructor with optional parameters angular angular

DI constructor with optional parameters


Just add the @Optional() decorator before the constructor parameter that should only be injected if there was a provider registered.

import { Optional } from '@angular/core';    constructor(public name:string, @Optional() public age:number)


If I understand correctly what you are trying to do, you need a service factory. See here: https://angular.io/docs/ts/latest/guide/dependency-injection.html#factory-provider

Basically,

class MyClass {    constructor(public name:string, private _service:Service, public age?:number){}}

And then

let myFactory = (_service: Service) => {  return isAgeOk ? new MyClass(name, _service, age) : new MyClass(name, _service);};

And then you should provide your service like this:

providers: [{ provide: MyClass, useFactory: MyFactory, deps: [Service]}]