providing optional param to injectable service constructor - Angular2

1.1k Views Asked by At

There is AppComponent and SecurityService.

...
@Injectable()
export class SecurityService implements OnInit {    
    private _url: string;

    constructor(private http: Http, private name?: string) {
        this._wsUrl = 'http://myurl/' + this.name        
    }
...
}

AppComponent is one which will inject security service.

export class App {

    constructor(private security: SecurityService){

    }
    ... 
}

My question is: How can I provide this optional param value for the security service constructor?

1

There are 1 best solutions below

6
On BEST ANSWER

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

constructor(private http: Http,@Optional() private name: string) 

You can read more about Optional here

DEMO