angulartypescriptangular-router-params

providing optional param to injectable service constructor - Angular2


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?


Solution

  • 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